Why is test.elem undefined in this scenario?
The title gives the error I get when I use the following:
var test = {
elem : undefined,
init : function() { console.log("test.init() fired");
elem = $("#id开发者_如何学运维");
console.log("elem assigned to jQuery object");
elem.click(function() { console.log("elem clicked"); });
console.log("elem click handler created");
}
};
test.init();
test.elem.click();
I don't understand. If I run test.init()
where it assigns the value for test.elem
, why would it be undefined when I try to access it later?
You're creating a new reference called 'elem' inside of the init function rather than referencing test.elem.
Inside init you need to assign the element to 'this.elem', so it would read:
init : function() {
console.log("test.init() fired");
this.elem = $("#id");
console.log("elem assigned to jQuery object");
this.elem.click(function() {
console.log("elem clicked");
});
console.log("elem click handler created");
}
精彩评论