为什么这是错误的?
var ContactInfo = document.getElementById("Contact").children;
var i;
for (i = 0; i < 4; i++) {
ContactInfo[i].style.fontSize = "13px";
}
此代码执行后,函数中的其余代码将停止工作。这段代码在 onload 事件上执行。我尝试使用 Chrome 进行调试,我得到了这个: 未捕获的类型错误:无法读取未定义的属性“样式”。
当我用数字替换方括号 [ i ] 内的“i”时,循环有效。但后来我没有得到循环。
最佳答案
当您有一个 undefined variable 时会发生此错误。您很可能正在尝试索引比该节点更多的子节点。而是使用子列表的长度来限制 for 循环:
var contactInfo = document.getElementById("Contact").children;
for (var i = 0; i < contactInfo.length; i++) {
contactInfo[i].style.fontSize = "13px";
}
关于javascript - 未捕获的类型错误 : Cannot read property 'style' of undefined when using for loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31711739/