2017-04-12 50 views
2

我正在使用輸入字段和on(「keyup」)事件構建項目的篩選器。它看起來像這樣:使用Jquery搜索元素屬性,部分匹配

$("#inputFilter").on("keyup", filterPrograms); 

它的工作很好地類中找到的物品,如:

<h6 class="programName">Science</h6> 

然而,內一些人H6s的,我添加了一個數據屬性,像這樣:

<h6 class="programName" data-tag="indigenous interdisciplinary ">Aboriginal Studies</h6> 

如何修改以下代碼以過濾類的文本(當前正在工作)以及數據標記的內容?只要部分匹配不成立,就會隱藏父塊'.mix'。這裏是我的功能:

function filterPrograms(event) { 
     // Retrieve the input field text 
     var filter = $('#inputFilter').val(); 
     // Loop through the blocks 
     $(".programName").each(function(){ 
      // this part isn't working!! 
      dataResult = $(this).is('[data-tag*='+filter+']') < 0; 
      // If the item does not contain the text phrase, hide it 
      textResult = $(this).text().search(new RegExp(filter, "i")) < 0; 
      if (textResult || dataResult) { 
       $(this).closest(".mix").hide();   
      } else { 
       $(this).closest(".mix").show(); 
      } 
     }); 
    } 

現在,我敢肯定,這是因爲。是()永遠無法完全匹配,這就是爲什麼我需要一個部分匹配。在上面的例子中,輸入「indi」應該對數據標籤屬性的內容提供肯定的結果;這不起作用。鍵入「abo」匹配textResult,並且正常工作。

我知道我錯過了一些東西,但閱讀文檔(和SO)對此沒有幫助。提前致謝。

編輯:這裏與@三聯的解決方案的工作職能:

$(".programName").each(function(){ 
    // If the item does not contain the text phrase hide it 
    dataResult = $(this).is('[data-tag*="'+filter+'"]'); 
    textResult = $(this).text().search(new RegExp(filter, "i")) < 0; 
    if (textResult && !dataResult) { 
     $(this).closest(".mix").hide(); // Hide the item if there are no matches 
    } else { 
     $(this).closest(".mix").show(); // Show the item if there are matches 
    } 
}); 

回答

1

好一件事,你不能比較的.is()0這樣的結果。 is()返回一個布爾值。

所以改變這一點。

dataResult = $(this).is('[data-tag*='+filter+']') < 0; 

對此。

dataResult = $(this).is('[data-tag*="'+filter+'"]'); 

請注意,我還引用了屬性匹配的字符串,這將允許查詢包含空格。

+1

這很好。非常感謝! – oliverh72