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

この1つは、完璧な作品試しください!どうもありがとうございました。私が入力しているとき、今はちょっとちらちらです。遅延を伴ってキーアップ機能を実行する方法を知っていますか?これで全体が少しスムーズになります:) – David

+0

ようこそ私は考えてみましょう。私は答えを更新します –

+0

いいね!どうもありがとうございます! :) – David

関連する問題