2016-09-23 47 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