javascript - 搜索多个属性

标签 javascript jquery search attr

我有一个搜索功能,可以非常愉快地在列表 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);
        }
    });

最佳答案

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

关于javascript - 搜索多个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13935505/

相关文章:

c# - 密码正则表达式适用于 chrome 和 firefox,但不适用于 IE7

javascript - Chrome 控制台 - 这个代表 Kendo UI 小部件的东西实际上意味着什么?

javascript - GiantBomb API 工作

search - 在 J 中使用向量/矩阵时打印值及其关联索引

javascript - 不能在 node.js 中使用模板字符串

jquery - 在 JQuery 中创建一组函数

javascript - 在 div 内以 100% 步长滚动

javascript - 如何为没有内容的单个选项卡着色?

javascript - 在字段中键入和粘贴之间的区别

javascript - 很难理解回调函数