搜索多个属性

4

我有一个搜索功能,可以轻松地搜索一个包含data-attribute的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(..) - EricG
3个回答

2
你可以使用 .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()


谢谢您提供的解决方案,我稍微有所改动,通过单独列出每个数据字段并逐一使用正则表达式进行测试,而不是使用数组,但似乎无法使其正常工作。将来我会再次查看它,以使其更好地运行。我已编辑我的描述,以显示对我有效的解决方案。 - dev

0

0

如果您事先不知道属性名称,或者您不想知道它们,只是想在要搜索值的任意一组属性中进行搜索,则可以使用以下方式

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接