当我访问子元素时,函数在循环后不继续

Function doesnt Continue after loop when I access child elements

这是我遇到问题的代码:

内文:

    <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("Something in the alert");

正在执行中?

问题出在 c[i].children[0] 未定义 中。这里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>

在您的代码中添加检查,如下所示:

 function myFunction(find) {
 var c = find.parentNode.children;
 var i;
 for (i = 0; i < c.length; i++) {
  if (c[i].children && c[i].children.length) {
   c[i].children[0].children[0].style.color = "red";
  }
 }
 alert("Something in the alert");
}
  
<!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>
</body>
</html>