- <!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>";
- <span style="background-color:rgb(204,204,204);"><span style="color:#993399;"><u>document.getElementById("demo").innerHTML=x;</u></span></span>
- }
- }
- </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>";
- }
- <span style="color:#993399;"><span style="background-color:rgb(204,204,204);">document.getElementById("demo").innerHTML=x;</span></span>
- }
- </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
这些问题都是一些很细枝末节的东西, 希望能帮和我有相同困惑的小伙伴拨开迷雾, 共勉!
来源: http://www.jianshu.com/p/29907905e523