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

标签 javascript jquery

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

相关文章:

javascript - 华丽的弹出窗口 : Why doesn't border radius work on the image and how can i make it work?

javascript - 滑动下划线边框以与事件网页配合使用

javascript - 如果不存在于另一个数组中,则从数组中移除

javascript - 如何更改 Google Analytics 中 "non-interaction"事件的默认值

jquery - bootstrap 3 旋转木马在骑自行车时高度缩小

javascript - 使用 $ 的变量声明

JavaScript 警报不显示

javascript - 智能 : Jump to declaration in node modules when TypeScript community stubs are present?

javascript - 使用窗口调整表格和文本的大小

javascript - 如何使用 HTML2Canvas 为 jQuery 元素截取屏幕截图?