【问题标题】:Searching through multiple attributes搜索多个属性
【发布时间】:2012-12-05 19:24:43
【问题描述】:

我有一个搜索功能,可以很高兴地通过列表 div 搜索一个数据属性,下面是正在工作的代码。

$(".classToSearch").each(function(){
    if ($(this).attr('data-attribute1').search(new RegExp(filter, "i")) < 0) {
        $(this).animate({opacity:0.1},100);
    } else {
        $(this).animate({opacity:0.5},100);
    }
});

我希望搜索功能能够搜索多个数据属性。我尝试了一系列不同的格式,但我无法让它工作。下面是我认为它应该看起来的样子。

$(this).attr('data-attribute1','data-attribute2','data-attribute3')

$(this).attr('data-attribute1'||'data-attribute2'||'data-attribute3')

但我想我需要某种 for 循环。任何帮助,将不胜感激。

---------编辑-------------

我的解决方案 这允许搜索框搜索所有数据属性。

$(".classToSearch").each(function(){
        if ($(this).attr('data-attribute1').search(new RegExp(filter, "i")) < 0 &&
            $(this).attr('data-attribute2').search(new RegExp(filter, "i")) < 0 &&
            $(this).attr('data-attribute3').search(new RegExp(filter, "i")) < 0 &&         
            ) {
            $(this).animate({opacity:0.1},100);
        } else {
            $(this).animate({opacity:0.5},100);
        }
    });

【问题讨论】:

  • 你的意思是例如if( $(this).attr('data-attr1').search(..) || $(this).attr('data-attr2').search(..) ) {} else {}?我只是提出建议,也许甚至可以做到[ $(this).attr('data-attrib1'), $(this).attr('data-attr2'), $(this).attr('data-attr3') ].search(..)

标签: javascript jquery search attr


【解决方案1】:

您可以使用.data() 更轻松地访问这些属性,然后将它们收集到一个数组中,您可以从中对每个属性执行正则表达式测试:

var $this = $(this),
attribs = [$this.data('attribute1'), $this.data('attribute2'), $this.data('attribute3')],
re = new RegExp(filter, "i");

if (attribs.some(function() {
    return this.match(re);
})) {
    // some attributes matched the filter
} else {
    // no attributes matched the filter
}

另请参阅:Array.some()

【讨论】:

  • 感谢这个解决方案,我通过分别列出每个数据字段并用正则表达式逐个测试它们来实现它有点不同,我似乎无法通过使用它来工作数组。将来我会再看一遍,让它更好地工作。 **我已经编辑了我的描述以显示对我有用的解决方案。 **
【解决方案2】:

你看过这个吗……

http://api.jquery.com/multiple-attribute-selector/

似乎是你所追求的。

但也许更像...

if ($(this).has([attr1],[attr2])){
   //do stuff
}

【讨论】:

    【解决方案3】:

    如果您不提前知道属性名称,或者您不想知道它们,只需在其中搜索值的任意一组属性,然后像这样

        $(".classToSearch").each(function() {
            var _in = $(this).text();
            $.each($(this).data(), function(k, v) {
                if (v == find) {
                    // ...
                }
            });
        });
    

    在 JSFiddle 中:http://jsfiddle.net/yJLzQ/1/

    【讨论】:

      猜你喜欢
      • 2012-08-02
      • 2014-11-02
      • 2013-01-23
      • 1970-01-01
      • 2016-07-30
      • 2018-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多