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