4

我有一个搜索功能,可以很高兴地通过列表 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);
        }
    });
4

3 回答 3

2

You could use .data() to access those attributes a little easier and then collect them into an array from which you perform the regular expression test on each of them:

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
}

See also: Array.some()

于 2012-12-18T15:00:05.640 回答
0

你有没有看过这个...

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

似乎是你的追求。

但也许更像...

if ($(this).has([attr1],[attr2])){
   //do stuff
}
于 2012-12-18T14:53:10.297 回答
0

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

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

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

于 2012-12-18T16:28:21.890 回答