javascript数组和循环
问题描述:
我是jessi,我是一名网络开发学生。我正在尝试编写一个程序与数组,我卡住了。我有一组短语,当用户输入一个介于1到10之间的数字时,它应该显示屏幕上有很多短语,但我被卡住了。我不知道如何在屏幕上显示多个结果。我非常感谢任何帮助。谢谢。javascript数组和循环
<!DOCTYPE html>
<html>
<head>
<title>Get A Response</title>
</head>
<body>
<form>
<h1>Select how many phrases you want displayed.</h1>
<input type="number" class="userInput"></input>
<button type="submit" value="submit" onclick="showme()"></button>
</form>
<div class="myphrases">
</div>
<script src="js/main.js"></script>
</body>
</html>
////////////////// Javascript
function showme() {
var number = document.querySelector('.userInput').value;
var display = "";
var phrases = [
"Hello there",
"What's up Doc",
"Because I said so",
"Say it again",
"It's a celebration",
"Enjoy yourselves",
"Welcome",
"Where did you go", "Why you crying", "Stop playing"];
var random = Math.floor(Math.random() * phrases.length);
for(var i = 0; i < phrases.length; i++) {
}
}
答
:
首先,您应该设置一个HTML元素作为您的输出区域。一个空的div
元素是一个不错的选择。你已经完成了:<div class="myphrases"></div>
。
接下来,HTML input
元素没有得到关闭标签(</input>
)和,而不是使用submit
按钮,只需使用常规的按钮(因为你实际上并没有提交任何位置的数据)。
另外,不要使用内嵌HTML事件处理属性(的onclick,的onmouseover,等等),因为它们:
- 创建导致重复,使得代码难以阅读面条代码。
- 导致围绕您的属性值创建全局匿名包装函数,并在您的回调函数中更改
this
绑定。 - 请勿遵循使用
.addEventListener()
的W3C事件标准。
接下来,没有循环遍历每个短语(phrases.length
)。只有用户输入的次数。
// Get reference to the text box, the button and the output area
var number = document.querySelector('.userInput');
var btn = document.querySelector("button");
var output = document.querySelector(".myphrases");
// Set up the event handling function for the button
btn.addEventListener("click", showme);
function showme() {
var display = "";
var phrases = [
"Hello there",
"What's up Doc",
"Because I said so",
"Say it again",
"It's a celebration",
"Enjoy yourselves",
"Welcome",
"Where did you go", "Why you crying", "Stop playing"];
// String to hold loop results
var result = "";
// Set up the upper limit for the loop.
// If the entered value is greater than the length of the array, use the length
// of the array. If not, use the value entered by the user
var count = number.value > phrases.length ? phrases.length : number.value;
for(var i = 0; i < count; i++) {
var random = Math.floor(Math.random() * phrases.length);
result += phrases[random] + "<br>";
}
// Inject the string into the output area
output.innerHTML = result;
}
<form>
<h1>Select how many phrases you want displayed.</h1>
<input type="number" class="userInput">
<button type="button">Submit</button>
</form>
<div class="myphrases"></div>
最后,您可以通过调整其innerHTML
是,你从你的循环建立一个字符串更新div
输出区域