javascript - 未捕获的类型错误 : Cannot read property 'style' of undefined when using for loop

标签 javascript css

为什么这是错误的?

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/

相关文章:

带有 jQ​​uery 的 Safari 和 Firefox 中的 Javascript(严格)错误

javascript - 在 jquery 日期选择器上应用 .ui-datepicker-trigger 类

javascript - JS 未在本地主机中加载

html - Bootstrap 中的 .row 类是如何定义的?

javascript - 如何使用查询更改 tinymce 背景 onchange 的颜色

javascript - 我可以修改 ReactJs 中组件的父状态吗?

javascript - 删除jquery中没有特定后代元素的所有元素

javascript - jQuery 序列化顺序似乎是随机的

html - CSS 显示 : table - How can I line up two cells to be in the center of another DIV using display: table?

未应用 CSS 媒体查询