2016-09-23 11 views
0

jQuery 및 쉼표로 구분 된 키워드로 실시간 검색을 만들려고합니다. 텍스트 필드의 전체 문자열 만 키워드로 사용하는 경우 검색은 매력처럼 작동합니다. (단일 키워드에 대한 작업)쉼표로 구분 된 키워드로 jQuery 텍스트 필드 라이브 검색

코드 :

내가 지금 할 노력하고 무엇
jQuery("#artikelfilter").keyup(function(){ 

    // Retrieve the input field text and reset the count to zero 
    var filter = jQuery(this).val(), count = 0; 

    // Loop through the comment list 
    jQuery("#liste-alles li").each(function(){ 

     // If the list item does not contain the text phrase fade it out 
     if (jQuery(this).text().search(new RegExp(filter, "i")) < 0) { 
      jQuery(this).fadeOut(); 

     // Show the list item if the phrase matches and increase the count by 1 
     } else { 
      jQuery(this).show(); 
      count++; 
     } 
    }); 

    // Update the count 
    var numberItems = count; 
    jQuery("#filter-count").text("Number of Comments = "+count); 
}); 

, 복수 키워드로 필터링하는 것입니다. 문자열을 배열로 나누고 키워드를 반복하는 방법에 대해 생각했습니다. 문제는 jQuery 이벤트가 많아서 브라우저가 더 이상 처리 할 수 ​​없다는 것입니다.

이 작업을 수행하는 현명한 방법이 있습니까? 여러 키워드에 대한

코드는 (작동하지 않는) :

jQuery("#artikelfilter").keyup(function(){ 

    // Retrieve the input field text and reset the count to zero 
    var string_filter = jQuery(this).val(); 
    var array_filter = string_filter.split(','); 

    // Loop through the comment list 
    jQuery("#liste-alles li").each(function(){ 

     jQuery.each(array_filter, function(intValue, currentFilter) { 
      // If the list item does not contain the text phrase fade it out 
      if (jQuery(this).text().search(new RegExp(filter, "i")) < 0) { 
       jQuery(this).fadeOut(); 

      // Show the list item if the phrase matches and increase the count by 1 
      } else { 
       jQuery(this).show(); 
      } 
     }); 

    }); 

}); 

감사합니다!

답변

1

jQuery.each(array_filter, function(intValue, currentFilter) { 
    jQuery("#liste-alles li:contains("+currentFilter +")").show(); 
    jQuery("#liste-alles li:not(:contains("+currentFilter +"))").fadeOut(); 

}); 

또는이

var regex = new RegExp(filter, "i")); 

jQuery.each(array_filter, function(intValue, currentFilter) { 

    jQuery("#liste-alles li").filter(function() {return regex.test($(this).text()); }).show(); 
    jQuery("#liste-alles li").filter(function() {return !regex.test($(this).text()); }).fadeOut(); 

}); 
+0

이 하나가 완벽하게 작동보십시오! 고맙습니다. 이제 타이핑 할 때 조금 깜박입니다. 지연으로 키업 기능을 실행할 수있는 방법을 알고 있습니까? 이것은 모든 것을 조금 더 매끄럽게 만들 것입니다. :) – David

+0

환영합니다 : 생각해 봅시다. 그리고 대답을 업데이트 할 것입니다. –

+0

좋은 소리! 정말 고맙습니다! :) – David