gpt4 book ai didi

javascript - 所有 jQuery 对象的公共(public)属性

转载 作者:行者123 更新时间:2023-11-29 18:32:30 25 4
gpt4 key购买 nike

我想在我的对象中创建一个属性,其中包含它将使用的所有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com