我正在尝试使用 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();
}
});
});
});
谢谢!