2

我最近一直在开发一些 JS 重度网站,虽然我大部分时间都喜欢使用纯 JS,但 jQuery 毫无疑问有它的用途,我现在主要依靠它来快速事件绑定/冒泡。我的问题是关于使用 jQuery 缓存对象以及如何最好地使用它们。

我发现自己在我的大部分 js 脚本中都在做这些事情。

jQuery.noConflict();

var doc = jQuery(document), // Root jQ object
    html = doc.children('html'), // Mainly to check modernizr classes
    container = html.find('.container'); // Base content container

/** module 1 **/
(function($, w, undefined) {

    container.on('click', 'button', function(e) {
        ...
    });

})(jQuery, window);

/** module 2 **/
(function($, w, undefined) {

    container.on('click', 'a.module', function(e) {
        // Occasionally creating further jQ objects in contextual situations
        var self = $(this);

        // Or is this better
        var clicked = container.find(this);
    });

})(jQuery, window);

如您所见,我只有一个高级 jQuery 对象用于遍历 DOM,同时偶尔会在上下文需要的地方创建新的 jQuery 对象。我玩弄了使用插件的想法,jQuery.single尽管我真的觉得没有必要。

这实际上对我有什么好处吗,我觉得这更好,因为我只创建了尽可能少的 jQuery 对象而不使用 jQuery 单一(参见第二个模块代码),尽管我不能确定。我希望这里的某个人能够阐明这是否可行,或者我应该坚持我以前的方法,在我的每个单独的闭包中创建 jQuery 对象?

我以前的方法的例子

/** module 1 **/
(function($, w, undefined) {

    var container = $('.container');

    container.on('click', 'button', function(e) {
        ...
    });

})(jQuery, window);

/** module 2 **/
(function($, w, undefined) {

    var container = $('.container');

    container.on('click', 'a.module', function(e) {
        // Occasionally creating further jQ objects in contextual situations
        var self = $(this);
    });

    // Usually if I needed anything further outside the container
    // If create further objects
    var header = $('header');

})(jQuery, window);
4

0 回答 0