[英]I'm trying to print all even numbers from 10 to 40 using just a while loop in Javascript
[英]Using a for loop in javascript with a onclick function to print numbers 1 to 10
我對這一切都很陌生,我需要創建一個 JavaScript 循環,當單擊一個按鈕時打印出數字 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:</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>
嘗試這個
<!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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.