我对这一切都很陌生,我需要创建一个JavaScript for循环,当点击一个按钮时打印出数字1到10,当点击另一个按钮时打印出数字-1到-10,如所附的屏幕截图所示。
我已经这样做了,但我被卡住了。
<!DOCTYPE html>
<html>
<body>
<h1>For loop statement exercise</h1>
<p>Press PLUS to display +1 to +10:
<button onclick="plus()">PLUS</button>
<p>Press MINUS to display -1 to -10:
<button onclick="myFunction()">MINUS</button>
<p id="i"></p>
<script>
for (i = 1; i <= 10; i++)
{
document.write("i" + < br > );
}
</script>
</body>
</html>
试试这个
<!DOCTYPE html>
<html>
<body>
<h1>For loop statement exercise</h1>
<p>
Press PLUS to display +1 to +10: <button onclick="plus()">PLUS</button>
</p>
<p>
Press MINUS to display -1 to -10:
<button onclick="minus()">MINUS</button>
</p>
<p id="i"></p>
<script>
function minus() {
for (i = -1; i >= -10; i--) {
document.getElementById("i").innerHTML =
document.getElementById("i").innerHTML + `${i} <br>`;
}
}
function plus() {
for (i = 1; i <= 10; i++) {
document.getElementById("i").innerHTML =
document.getElementById("i").innerHTML + `${i} <br>`;
}
}
</script>
</body>
</html>
我不知道您是否希望它在每次单击时添加一个数字,或者在一次单击中添加所有数字,但我做到了:
<!DOCTYPE html>
<html>
<body>
<h1>For loop statement exercise</h1>
<p>Press PLUS to display +1 to +10:</p>
<button onclick="plus()">PLUS</button>
<p id="+"></p>
<p>Press MINUS to display -1 to -10:</p>
<button onclick="minus()">MINUS</button>
<p id="-"></p>
<script>
function plus() {
for(let i = 1; i <= 10; i++) {
document.getElementById("+").innerHTML += i + " ";
}
}
function minus() {
for(let i = -1; i >= -10; i--) {
document.getElementById("-").innerHTML += i + " ";
}
}
</script>
</body>
</html>