【问题标题】:Restrict selector to a Set of Elements (jquery object)将选择器限制为一组元素(jquery 对象)
【发布时间】:2014-03-08 06:03:48
【问题描述】:

我正在寻找这种功能:$(restrictTo).findAlsoSelf('.box').doSomethingWithTheMatches()

restrictTo 是一个 jquery 对象(a jQuery object represents a set of DOM elements)。所以我只希望我的选择器应用于restrictTo 参数定义的元素集。

.find() 仅适用于每个元素的子元素。我还需要元素本身来尝试匹配。

Demo: jsFiddle

演示使用.on() 方法,您可能会说我可以写

$(document).on('click', '.box', function() { ...

获得我正在寻找的功能。 但是我不想双重绑定或弄乱可能已经加载的内容。

.color-box 就是一个很好的例子。我只希望我刚刚添加的那个变黄。已经在页面底部和.content 顶部的那个应该保持绿色。


我能想到的最接近的是:

$(restrictTo).find('.color-box').add($(restrictTo).siblings('.color-box')).doSomethingWithTheMatches()

但这也匹配该 dom 级别中已经存在的任何同级(参见演示的.content 区域中的.color-box

也许是我想太多了。我以为我对 jQuery 很熟悉,但我就是想不出一个干净的解决方案。

实际项目使用requireJS 和用于车把模板和css 的requireJS 插件。所有代码都变得模块化。因此,一旦模板被渲染,我需要绑定并添加 javascript 以配合该 sn-p。我确实有一个附加方法,我调用了require(['modules/tiny-module/tiny.bits']);,但问题是如果我需要多次加载tiny-moduletiny.bits.js 脚本仅在tiny-module 被加载到页面时执行一次第一次加载,并且永远不会附加到新加载的 dom。

一旦我弄清楚了restrictTo 这个东西,我基本上会在每个模块的 attach 方法中调用bind() 方法,该方法实际上会在每次连续加载模块时执行。


编辑:我的回答没有解决它,但我只想记录它。它不适用于this edge case

jQuery.fn.findAlsoSelf = function(selector) {
    return this.find(selector).add(this.filter(selector));
};

@phenomnomnominal 的答案很棒,并且适用于两个演示。

【问题讨论】:

    标签: javascript jquery binding jquery-selectors


    【解决方案1】:

    我想你想要的是这样的:

    jQuery.fn.filterFind = function(selector) { 
        return this.find('*')         // Take the current selection and find all descendants,
                   .addBack()         // add the original selection back to the set 
                   .filter(selector); // and filter by the selector.
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 2011-10-23
      • 1970-01-01
      • 2018-06-14
      • 1970-01-01
      • 2022-10-02
      相关资源
      最近更新 更多