JavaScript 循环输出
JavaScript Loop Output
all.我是 JavaScript 的新手,所以希望这对你们来说是一个非常简单的问题。但我绝对,为了我的生活,不知道该怎么做!我正在创建一个时间表程序,我需要输出看起来像这样:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
...
。等等。但是,每当它输出到屏幕时,它只显示循环的 LAST 输出。所以它将显示"5 x 12 = 60"。我需要它在每次程序通过循环时显示每个单独的输出。我将如何做到这一点?
提前非常感谢!
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<!--
Input
User clicks the "Compute Table" button.
Processing
The computer creates a times table based on the users' input.
Output
Outputs the table to the user.
-->
<title>Times Table</title>
<script>
function computeTable() {
// Declaring some variables and pulling the integer from the HTML form. Nothing to see here.
var integer = parseInt(document.getElementById('input').value);
var i = 1;
// Running the loop and doing all the arithmetic
while (i < 12) {
i++;
}
// This line displays the output to the user
var output = document.getElementById('outputdiv');
output.innerHTML = integer + " x " + i + " = " + (integer * i);
}
</script>
</head>
<body>
<h1>Times Table</h1>
Please enter a positive integer: <input type="text" id="input">
<button type="button" onclick="computeTable()">Compute Table</button>
<hr>
<div id="outputdiv" style="font-weight:bold"></div>
</body>
</html>
每次变量递增时,您都需要更新div。
var output = document.getElementById('outputdiv');
while (i < 12) {
output.innerHTML = integer + " x " + i + " = " + (integer * i);
i++;
}
虽然我认为它会很快更新您的结果,您可能无法看到每个结果。 也许你想要这样的东西?
var output = document.getElementById('outputdiv');
var html;
if (output.innerHTML.length != 0) {
output.innerHTML = "";
}
while (i < 12) {
html = output.innerHTML;
html += (i > 1 ? ", " : "") + integer + " x " + i + " = " + (integer * i);
output.innerHTML = html;
i++;
}
这应该给你带来类似result_1, result_2, result_3, //etc.
这是一个工作示例。 此外,正如Johnannes在他的回答和评论中指出的那样,更新内部HTML可以直接完成output.innerHTML += value;
这里有多个问题。
1)你只输出一次——所以无论你做什么,都只有一行。声音很合理,对吧?
2) 即使您多次输出,output.innerHTML = "..."
也会覆盖任何以前的分配。'因为它是一个分配,它不会附加。
因此,解决方案在循环内挂起:
var i = 1;
while ( i < 12 ) {
output.innerHTML += integer + " x " + i + " = " + (integer * i) + "<br>";
i++;
}
这可以通过更短的方式完成,使用 for
循环:
for (var i = 1 ; i < 12 ; i++) {
output.innerHTML += integer + " x " + i + " = " + (integer * i) + "<br>";
}
相关文章:
- 如何将angularjs中的javascript字符串输出为循环数组
- 一个ajax循环有两个输出错误innerHTML
- 循环时输出额外+;javascript
- for 循环使输出并排 jQuery
- for语句循环小写输出
- 如何在 p5.js 中将 For 循环的文本输出替换为不同的值
- 如何使用嵌套循环使用 Javascript 打印到外部循环的输出中
- 无法让 JSON 输出循环
- 当在 Javascript 中使用许多 for 循环时,输出是未定义的
- JavaScript 循环输出
- JavaScript 循环输出顺序不正确 - 如何解决这个问题
- For 循环不迭代,输出的数据不超过第一个任务
- 循环遍历json_encode的输出
- 在 HTML 中循环写入(输出)语句
- 如何让 jquery 在循环中的每个 ajax 调用后立即附加输出
- 为什么 javascript 对象在循环遍历数组时输出为“未定义”
- 如何循环显示来自跟踪路由输出的谷歌地图v3中的标记
- 将所有输出放在 JavaScript 中 while 循环中的特定文本框中
- Angular延迟实现只输出循环的最后一个值
- 使用for(..)遍历数组时的意外输出)循环