码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-06-25 11:48:09      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:col   htm   var   而不是   代码   element   script   size   java   

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

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

标签:col   htm   var   而不是   代码   element   script   size   java   

原文地址:https://www.cnblogs.com/newcapecjmc/p/11081818.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!