jQuery文本字段实时搜索,以逗号分隔的关键字

时间:2016-09-23 08:17:42

标签: jquery search filter textinput keyword-search

我正在尝试使用jQuery和逗号分隔的关键字创建实时搜索。 如果我只将text-field中的完整字符串作为关键字,则搜索就像魅力一样。

代码(适用于单个关键字):

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 个答案:

答案 0 :(得分: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();

});
相关问题