我在页面上显示for循环时出现问题。有一个按钮,在点击提示用户输入数字时,然后通过for循环显示所述数字的迭代。我已经查看了此处提出的类似问题,但似乎仍然遇到问题。
<!doctype hmtl>
<html>
<head></head>
<button onclick="getNumber()">Click!</button>
<p id="demo"></p>
<script>
function getNumber() {
var i;
var num;
var n = prompt("Please enter a number");
for(i = 0; i < n.length; i++){
num += n[i];
document.getElementById("demo").innerHTML += num + " ";
}
}
</script>
</body>
</html>
答案 0 :(得分:1)
应该{{1}}而不是i < n
。因为您正在进行的循环次数与变量i < n.length
中的字符循环次数(顺便说一句,这是一个字符串)。因此,如果用户键入n
,则只打印一个数字,因为9
为1,并且在0和1之间只有一次迭代(排除)。试试这个:
"9".length
答案 1 :(得分:1)
不确定您到底在尝试什么,但如果您想重复循环直到用户输入输入,您可以按照以下步骤进行操作
检查此代码段
function getNumber() {
var i;
var num;
var n = prompt("Please enter a number");
for (i = 0; i < n; i++) {
document.getElementById("demo").innerHTML += i + " ";
}
}
&#13;
<button onclick="getNumber()">Click!</button>
<p id="demo"></p>
&#13;
希望有所帮助
答案 2 :(得分:1)
您试图直接获取用户输入值的length
属性而不是值。
此外,您的代码中有几个不必要的位以及一些对性能产生负面影响的不良操作。
// Get a reference to the HTML (DOM - Document Object Model) elements that
// you will need access to at this level of scope
var btn = document.getElementById("btn");
// Don't set up event handling code in the HTML (a.k.a. inline event handling) as it
// makes the HTML harder to read (two languages on a single line), it doesn't follow
// the standard for event handling, and it causes anonymous Global JavaScript functions
// to be made as wrappers around the HTML attribute values. Instead, do it in JavaScript
// like this:
btn.addEventListener("click", getNumber);
function getNumber() {
// Just scan for the element once, not each time the loop iterates
var el = document.getElementById("demo");
// Get the user's input and convert it to a number
var n = parseInt(prompt("Please enter a number"), 10);
// Set up a string that will become the output.
var output = "";
for(var i = 0; i < n; i++){
// NEVER alter an HTML (DOM) element within a loop as performance suffers
// because the browser must recreate the entire DOM structure.
// Instead, set up a variable that holds the results
output += " " + i;
}
// Once loop is done, update element with the variable. But, this way,
// you are doing it just once, instead of each time the loop iterates.
// Also, if the new content does not include HTML, then use textContent
// instead of innerHTML as it lets the browser know that the data does
// not have to be parsed, which results in a quicker update.
el.textContent = output;
}
<button id="btn">Click!</button>
<p id="demo"></p>
答案 3 :(得分:1)
问题在于n.length
部分。想象一下,用户提供数字“10”。数字10的长度属性为2,因此循环内的代码执行2次而不是10次。
<html>
<head>
</head>
<button onclick="getNumber()">Click!</button>
<p id="demo"></p>
<script>
function getNumber() {
var i;
var num;
var n = parseInt(prompt("Please enter a number"));
for(i = 1; i <= n; i++){
document.getElementById("demo").innerHTML += " " + i;
}
}
</script>
</body>
</html>