2012-12-18 88 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/