首页 > 解决方案 > 当我访问子元素时,函数在循环后不继续

问题描述

这是我面临问题的代码:

内部:

    <div id="test">

        <p>Hello World! <b> Some Bold <i> RED(and also Italic)</i>
            </b>
            <i>text</i>
        </p>

        <button onclick="myFunction(this)">Try it</button>

        <p id="demo"></p>

    </div>

内部脚本

    function myFunction(find) {
        var c = find.parentNode.children;
        var i;
        for (i = 0; i <= c.length; i++)
        {
            c[i].children[0].children[0].style.color="red";
        }
          alert("Something in the alert");
    }

我的问题是,为什么不

alert("警报中有内容");

正在执行?

标签: javascriptloopschildren

解决方案


问题出在c[i].children[0] is undefined中。这里 javascript 停止执行。

所以使用 try catch 方法来处理这种情况。

<!DOCTYPE html>
    <html>
    <body>
    <div id="test">

        <p>Hello World! <b> Some Bold <i> RED(and also Italic)</i>
            </b>
            <i>text</i>
        </p>

        <button onclick="myFunction(this)">Try it</button>

        <p id="demo"></p>

    </div>

    <script>

    function myFunction(find) {
        var c = find.parentNode.children;
        var i;
        for (i = 0; i <= c.length; i++)
        {
            try {
            c[i].children[0].children[0].style.color="red";
          }
          catch(err) {
          }
        }
          alert("Something in the alert");
    }

    </script>

    </body>
    </html>

推荐阅读