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

  • 相关阅读:
    Android中Webview与javascript的交互(互相调用)
    Android EditText横屏时软键盘不占据全屏
    Android 获取当前IP地址
    Android Dialog监听返回键!
    Android 显示特殊符号
    给EditText的drawableRight属性的图片设置点击事件
    Android 获取静态上下文(Application)
    Android dp和px之间进行转换
    Android 透明状态栏
    Android平台实现与Apache Tomcat服务器数据交互(MySql数据库)
  • 原文地址:https://www.cnblogs.com/newcapecjmc/p/11081818.html
Copyright © 2020-2023  润新知