JavaScript同位素 - 如何智能地创建多组过滤器以在一个容器上协同工作?

jon*_*omo 2 javascript jquery jquery-isotope

让我们说我想过滤颜色(红色,黄色或蓝色)和尺寸(小,中或大)和材料(羊毛,棉,丝).我将有三套复选框.如果用户选中"红色"复选框和"中"复选框,我希望Isotope显示红色和中等的项目.到目前为止,没问题.但是,如果用户检查红色和黄色复选框以及中型和大型复选框以及羊毛和丝绸复选框,该怎么办?现在我希望Isotope显示的是((medium OR large) AND (red OR yellow) AND (wool OR silk)).

构建一个jQuery选择器字符串以适应这种情况对我来说似乎很复杂,特别是如果有几十个组,每个组包含几十个选项.

仅使用jQuery,我可以执行以下操作:

$('.medium, .large').filter('.red, .yellow').filter('.wool, .silk');
Run Code Online (Sandbox Code Playgroud)

但是如果我只需要构建整个选择器一次以将其完全形成传递给Isotope,我将不得不这样做:

`.medium.red.wool, .medium.red.silk, .medium.yellow.wool, .medium.yellow.silk, .large.red.wool, .large.red.silk, .large.yellow.wool, .large.yellow.silk`
Run Code Online (Sandbox Code Playgroud)

如您所见,从三个组中选择了两个项目,我的选择器中有2 ^ 3个以逗号分隔的字符串.现在假设我有六个过滤组:

Color (red, blue, yellow, green, purple, black)
Size (tiny, small, medium, biggish, large, extra-large)
Price (very-cheap, cheap, medium, expensive, very-expensive, extraordinarily-expensive)
Material (cotton, wool, satin, linen, felt, wood, iron)
Type (archer, hunter, wizard, mage, spy, druid)
Popularity (not-popular, mildly-popular, somewhat-popular, medium-popular, quite-popular, very-popular)
Run Code Online (Sandbox Code Playgroud)

让我们说用户检查每组中的前五个选项.我的选择器字符串必须包含5 ^ 6个以逗号分隔的字符串,每个字符串包含六个术语.如果每个术语平均5个字符,用5个字符.分隔它们,那么我将有5 ^ 6个字符串,每个35个字符长,我的选择器的总长度大约为546,875个字符.

Isotope是否为我提供了解决此问题的更好方法?

Esa*_*ija 5

jQuery也.filter接受一个函数,而不仅仅是一个选择器字符串,所以你可以创建一个函数.

$elem.isotope({
    filter: function() {
        var $this = $(this);
        return $this.is('.medium, .large') && $this.is('.red, .yellow') && $this.is('.wool, .silk');
    }
});
Run Code Online (Sandbox Code Playgroud)

看同位素源代码,它似乎应该工作,因为它们将filter参数传递给jQuery过滤器方法.

你可以通过传递一个选择器数组来实现这样的功能:

function makeFilterFunction( selectorsArray ) {
    var length = selectorsArray.length;
    return function() {
        var $this = $(this);

        for( var i = 0; i < length; ++i ) {
            if( !$this.is( selectorsArray[i] ) ) {
                return false;
            }
        }

        return true;
    };
}
Run Code Online (Sandbox Code Playgroud)

然后:

$elem.isotope({
    filter: makeFilterFunction(['.medium, .large', '.red, .yellow', '.wool, .silk'])
});
Run Code Online (Sandbox Code Playgroud)

在我的答案开头是动态等效的静态代码.