<!DOCTYPE html>
<html>
<body>
<p>點擊下面的按鈕,將代碼塊循環五次:</p>
<button onclick="myFunction()">點擊這里</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x="";
for (var i=0;i<5;i++)
{
x=x + "The number is " + i + "<br>";
document.getElementById("demo").innerHTML=x;
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p>點擊下面的按鈕,將代碼塊循環五次:</p>
<button onclick="myFunction()">點擊這里</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x="";
for (var i=0;i<5;i++)
{
x=x + "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>
上面兩段代碼是來自w3school中的一個關於for循環和標簽元素賦值的問題的例子,我是之前一直糾結於將document.getElementById("demo").innerHTML=x;放在for循環內外結果為什么一樣?
放在外邊的情況很好理解,無非是p標簽輸出了循環到最后的x的結果,即:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
而放在里面的情況,我之前一直認為是每循環一次p標簽輸出一次x的結果,即:
The number is 0
The number is 0
The number is 1
The number is 0
The number is 1
The number is 2
The number is 0
The number is 1
The number is 2
The number is 3
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
但這樣的想法是錯誤的,因為p標簽是閃現了5次輸出的結果,最后顯示的是最終輸出的x結果,而不是把每次的值都顯示出來,即:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
---------------------