未捕获的TypeError:无法读取属性' style'使用for循环时未定义的

时间:2015-07-29 21:44:57

标签: javascript css3

为什么这是错的?

Router.route('/org/:_id', {
name: 'org',
subscriptions: function() {
    return [
        Meteor.subscribe('contacts', this.params._id),
        Meteor.subscribe('organization', this.params._id)
    ];
},
onBeforeAction: function() {
    user = Meteor.user();
    if (!Roles.userIsInRole(user, ['admin'])) {
        this.redirect('/submit-ticket');
        this.stop();
    } else {
        this.next();
    }
},
action: function() {
    if (this.ready()) {
        Session.set('currentOrgId', this.params._id);
        this.layout('appLayout');
        this.render('orgHead', {
            to: 'orghead',
            data: function() {
                return Organizations.findOne({
                    _id: this.params._id
                });
            }
        });
        this.render('orgInfo', {
            to: 'content',
            data: function() {
                return Organizations.findOne({
                    _id: this.params._id
                });
            }
        });
    } else {
        this.layout('appLayout');
        this.render('loading', {
            to: 'content'
        });
    }
}
});

执行此代码后,函数中的其余代码将停止工作。这段代码在onload事件上执行。我尝试使用Chrome调试,我得到了这个: 未捕获的TypeError:无法读取属性' style'未定义的。

当我更换" i"括号内[i]带数字。但后来我没有得到循环。

2 个答案:

答案 0 :(得分:1)

如果您有未定义的变量,则会发生此错误。您很可能尝试索引比该节点更多的子项。而是使用子列表的长度来限制for循环:

var contactInfo = document.getElementById("Contact").children;
for (var i = 0; i < contactInfo.length; i++) {
    contactInfo[i].style.fontSize = "13px";
}

答案 1 :(得分:1)

如果您有4个以上的孩子怎么办?尝试:

var ContactInfo = document.getElementById("Contact").children;
var i;
for (i = 0; i < ContactInfo.length; i++) {
    ContactInfo[i].style.fontSize = "13px";
}