Custom jQuery filter needs optimization

后端 未结 3 537
我寻月下人不归
我寻月下人不归 2021-01-15 12:36

In the code below, friendBlocks has 800+ items that look like this:

Some Name &l
相关标签:
3条回答
  • 2021-01-15 12:51

    Do not apply the manipulation on each item in real-time! Clone the node, that contains the block divs, perform the operation, and then replace the original DOM.

    Something like (not tested, just example):

    friendform   = $('#container').clone();
    friendBlocks = friendform.find('.block');
    filterFriends = function(text) {
        friendBlocks.each(function() {
            var block;
            block = $(this);
            if (block.children('.title').text().toLowerCase().indexOf(text) >= 0) {
                block.show();
            } else {
                block.hide();
            }
        });
    };
    $('#container').replaceWith(friendform);
    
    0 讨论(0)
  • 2021-01-15 13:10

    This is noticeably much faster than your original code when tested in jsfiddle:

    var blocks = $('div.block');
    var foundBlocks = blocks.filter(function() {        
        return $('span.title', this).text().toLowerCase().indexOf(text) >= 0;
    });    
    foundBlocks.show();    
    blocks.not(foundBlocks).hide();
    

    JSFiddle Example

    I tried changing it so it cloned and then did the show/hide but I didn't notice any obvious difference in speed. Although this was chrome, other browsers may be slower.

    0 讨论(0)
  • 2021-01-15 13:10

    Not sure but I'd code something like this;

    $('.block .title').each(function(){
            var text = $(this).text();
            if (text.toLowerCase().indexOf(text) >= 0) { // not sure about here
                $(this).parent('div').show();
            } else {
                $(this).parent('div').hide();
            }
    });
    

    edit: code updated, not tried though. Coded this just to show selectors.

    0 讨论(0)
提交回复
热议问题