Javascript 搜索多个属性
我有一个搜索函数,可以很愉快地在列表div中搜索一个数据属性,下面是正在工作的代码Javascript 搜索多个属性,javascript,jquery,search,attr,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
$(".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);
}
});
或
但我想我需要某种形式的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);
}
});
$(“.classToSearch”).each(函数(){
if($(this).attr('data-attribute1').search(新的RegExp(filter,“i”))<0&&
$(this.attr('data-attribute2').search(新的RegExp(filter,“i”))<0&&
$(this.attr('data-attribute3').search(新的RegExp(filter,“i”))<0&&
) {
动画({opacity:0.1},100);
}否则{
设置动画({opacity:0.5},100);
}
});
你看过这个吗
似乎是你想要的
但也许有点像
if ($(this).has([attr1],[attr2])){
//do stuff
}
您可以使用.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
}
另请参见:如果您事先不知道属性名称,或者您不想知道它们,只需搜索任意属性集的值,然后执行类似的操作
$(".classToSearch").each(function() {
var _in = $(this).text();
$.each($(this).data(), function(k, v) {
if (v == find) {
// ...
}
});
});
在JSFiddle中:你是指例如
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(…)
感谢这个解决方案,我通过分别列出每个数据字段并用正则表达式逐个测试它们来实现它,我似乎无法通过使用数组使其工作。我以后会再看一遍,让它工作得更好一点**我已经编辑了我的描述,以显示适合我的解决方案**
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
}
$(".classToSearch").each(function() {
var _in = $(this).text();
$.each($(this).data(), function(k, v) {
if (v == find) {
// ...
}
});
});