我花了大约 3 个小时试图解决这个问题,但多次失败,我的代码最终只是恢复到这一点。
<html>
<head>
<title>Learning</title>
<script type="text/javascript">
function theMath(userOutput) {
document.getElementById("userOutput").innerHTML = userOutput
}
</script>
</head>
<body>
<p id="userOutput"></p>
<p> Counting from one to ten</p>
<input type="button" id="btnOutput" value="Add a number!" />
<p></p>
<script>
var strOutput = "";
var i;
for (i = 0; i <= 10; i++) {
strOutput = " " + i;
document.write(strOutput)
}
</script>
</body>
</html>
当前所有数字都出现在按钮下,但是我需要做的是,当我单击 btnOutput 时,会显示 for 循环的第一个数字 (0)。当我再次单击 btnOutput 时,将显示 for 循环的第二个数字 (1)。 因此,每次我单击 btnOutput 时,循环都会运行一次,直到无法再运行为止(当 i=11 时)
没有提到:for循环对于我正在做的事情是必要的。
最佳答案
您不需要 for 循环,只需增加数字并显示新数字即可。
var i = 1;
var maxValue = 11;
document.getElementById("btnOutput").addEventListener("click", function() {
if (i < maxValue) {
document.getElementById("userOutput").innerHTML += (i++) + "<br>";
}
});
<html>
<head>
<title>Learning</title>
</head>
<body>
<p id="userOutput"></p>
<p> Counting from one to ten</p>
<input type="button" id="btnOutput" value="Add a number!" />
<p></p>
</body>
</html>
关于javascript - 如何使用按钮激活 For 循环以显示每次按钮单击的每个单独结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46723324/