在下面的代码中,thebodyapp.body如何都可以成为JQuery对象,而在.css上设置thebody属性有效却在app.body上无效?

var app = app || {};

app.show = function(html) {
    this.baseElement.html(html);
};

app.body = $('body');

app.init = function() {
    this.baseElement = $('div#app');
    var thebody = $('body');
    console.log(app.objectIsJquery(thebody)); //true
    console.log(app.objectIsJquery(app.body)); //true
    app.body.css('background-color', 'yellow'); //does not set the background color, no errors
    //thebody.css('background-color', 'yellow'); //sets color correctly
};

app.start = function() {
    this.baseElement.css('color', 'brown');
    this.show(dp.qstr.addStar('testing'));
};


app.objectIsJquery = function(obj) {
    return obj.selector != undefined;
}

最佳答案

该代码可能在页面的顶部。因此,当执行app.body = $('body');行时,该主体尚不存在。但是随后您调用app.init();可能是在DOMReady上,所以主体在那时存在。运行var thebody = $('body');时,您会在集合中获得一个元素。

您可以通过检查app.body.length === 0thebody.length === 1来验证这一点。

您应该将整个代码块移到正文中或移到DOMReady回调中,例如:

$(function(){

...

});

10-05 21:06
查看更多