javascript中for循环和标签元素赋值问题总结

<!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
---------------------

posted @ 2019-06-25 11:27  朕在coding  阅读(2502)  评论(0编辑  收藏  举报