我想在我的对象中创建一个属性,其中包含它将使用的所有 jQuery 对象。我是 JavaScript 新手,这就是我需要建议的原因。我可以用这种方式做到这一点吗?
var myVar = {
init: function() {
//...
this.obj = {
id1: $('#id1'),
id2: $('#id2'),
id3: $('#id3')
}
this.method2();
},
method1: function() {
alert(this.obj.id1.html()) // some work with id1
},
method2: function() {
alert(this.obj.id1.html()) // some work with id1
}
};
$(function() {
myVar.init();
myVar.method1();
});
最佳答案
你的代码看起来不错。我可以预见到你的代码的唯一问题是 DOM 在运行时可能还没有准备好:
var myVar = {
init: function() {
//...
this.obj = {
id1: $('#id1'),
id2: $('#id2'),
id3: $('#id3')
}
},
method1: function() {
alert(this.obj.id1.html()) // some work with id1
},
method2: function() {
alert(this.obj.id1.html())
}
};
// run the init code (and any code that relies on init) after the DOM is ready
$(function() {
myVar.init();
myVar.method1();
});
示例: http://jsfiddle.net/2HppG/1/
(在示例中,我删除了 jsFiddle 默认提供的标准 DOM Ready 包装。)
关于javascript - 所有 jQuery 对象的公共(public)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6512050/