循环访问DOM子元素后函数终止,alert语句未执行的原因咨询
为什么
alert("Something in the alert");没有被执行? 先看看你的代码:
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++) { c[i].children[0].children[0].style.color="red"; } alert("Something in the alert"); }
问题出在你的循环逻辑和DOM节点访问的安全性上:
循环边界踩坑:
for (i = 0; i <= c.length; i++)这个条件是错误的。find.parentNode.children是类数组结构,它的有效索引范围是0到c.length - 1。当i等于c.length时,c[i]会变成undefined,这时候你去访问c[i].children[0]会直接抛出TypeError,脚本会立刻终止执行,后面的alert自然就没机会运行了。无判断直接访问深层节点:就算循环条件改对了,你直接链式访问
c[i].children[0].children[0]也很危险——不是所有子元素都有这么多层嵌套的(比如你的button元素就没有子节点),这种情况下同样会触发报错,导致脚本中断。
修复后的代码示例
function myFunction(find) { var c = find.parentNode.children; var i; // 修正循环边界,只遍历到最后一个有效索引 for (i = 0; i < c.length; i++) { // 逐层判断节点是否存在,避免报错中断脚本 if (c[i].children[0] && c[i].children[0].children[0]) { c[i].children[0].children[0].style.color="red"; } } alert("Something in the alert"); }
这样修改后,循环不会越界,还能跳过那些没有足够子节点的元素,脚本就能顺利执行到alert语句了。
内容的提问来源于stack exchange,提问作者Riaj Mahmud
相关产品推荐
相关产品推荐

