Filter multiple
    lists with jQuery

前端 未结 2 617
情书的邮戳
情书的邮戳 2021-02-05 09:51

I have multiple lists on one page (multiple categories of products) like this:

Category 1

  • item1<
2条回答
  •  粉色の甜心
    2021-02-05 10:05

    How about something like this:

    HTML

    
    
    
    • item1
    • item2
    • item3
    • item27
    • item28

    JS

    $(function(){
    
        $('input[type="text"]').keyup(function(){
    
            var searchText = $(this).val();
    
            $('ul > li').each(function(){
    
                var currentLiText = $(this).text(),
                    showCurrentLi = currentLiText.indexOf(searchText) !== -1;
    
                $(this).toggle(showCurrentLi);
    
            });     
        });
    
    });
    

    http://jsfiddle.net/EFTZR/146/

    Another solution using filter(), which is mentioned below:

    $('input[type="text"]').keyup(function(){
    
        var that = this, $allListElements = $('ul > li');
    
        var $matchingListElements = $allListElements.filter(function(i, li){
            var listItemText = $(li).text().toUpperCase(), 
                searchText = that.value.toUpperCase();
            return ~listItemText.indexOf(searchText);
        });
    
        $allListElements.hide();
        $matchingListElements.show();
    
    });
    

    http://jsfiddle.net/EFTZR/441/

提交回复
热议问题