2012-12-18 86 views
4

我有一个搜索功能,可以非常愉快地搜索一个数据属性的列表divs,下面是正在工作的代码。通过多个属性搜索

$(".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') 

但我想我会需要对某种循环。任何帮助,将不胜感激。

----------编辑-------------

我的解决方案 这使得搜索框来搜索所有的数据属性。

$(".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); 
     } 
    }); 
+0

你的意思是如如果($(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

回答

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()

+0

感谢这个解决方案,我已经实现它有点不同,分别列出每个数据字段并逐一测试它们,我似乎无法通过使用数组来实现它的工作。我会在将来再看这个,让它工作得更好一些。 **我编辑了我的描述以显示适用于我的解决方案。 ** – dev

0

如果你不知道属性名时间提前,或者你不想硝酸钾W¯¯他们的属性只是一个任意一组,你要搜索的值,那么像这样

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

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