我是11岁,刚开始学编程。我尝试使用while循环,并希望它以块的形式显示答案,而不是一大块。所以我尝试使用setTimeout,但它只会在一秒后显示第一行,然后立即将其余部分作为一个大块显示出来。此外,它会使用数字9作为临时变量,尽管我不知道那是从哪里来的。谢谢提前。
我希望保留代码中的while循环,因为我正在学习如何使用它们,所以如果您能在您的回答中保留while语句,那就太棒了!
以下是我的代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Made with Thimble</title>
<link rel="stylesheet">
</head>
<body bgcolor="lightblue">
<div id="d2">
Divisible by 2
</div>
<div id="d3">
Divisible by 3
</div>
<div>
<input id="seed" type="number" placeholder="seed" value="3"><br>
<input id="max" type="number" placeholder="max" value="8">
</div>
<button onclick="count()">Count</button>
<div id="output"></div>
<script>
function count() {
var seed = document.getElementById("seed").value
var max = document.getElementById("max").value
var temp = 1
var output = document.getElementById("output")
temp = seed
console.log("seed:" + seed)
console.log("max:" + max)
document.getElementById("output").innerHTML = " "
while (temp <= max) {
var intdivby2 = temp % 2
var intdivby3 = temp % 3
setTimeout(function() {
document.getElementById("output").innerHTML += "remainder of " + temp + " divided
by 2 is: "+intdivby2.toString()+" < br > "
document.getElementById("output").innerHTML += "remainder of " + temp + " divided
by 3 is: "+intdivby3.toString()+" < br > "
temp++
}, 1000)
}
}
</script>
</body>
</html>
setTimeout
,ajax等)吗?它与循环不太搭配。不过这会是学习递归的好动力。 - Bergi