Most efficient way to re-use jQuery-selected elements

后端 未结 4 2408
南方客
南方客 2021-02-20 17:14

I can imagine the correct answer to this based on theory, but I\'m just looking for some confirmation. I\'m wondering what the most efficient way to re-use a jQuery-selected ele

4条回答
  •  执念已碎
    2021-02-20 17:25

    One thing that I find is generally overlooked is just how powerful jQuery chains are. It may not be so noticeable, but since jQuery caches your wrapped elements within a chain, you can modify elements, go into a more specific subset, modify, then go back up into a a general superset without much overhead.

    I expect something like (pardon the example)

    $('#myDiv')
        .addClass('processing')
        .find('#myInput')
        .hide('slow')
        .end()
        .removeClass('processing')
        ;
    

    to be better performance-wise than even

    var $myDiv = $('#myDiv').addClass('processing');
    var $myInput = $('#myDiv #myInput').hide('slow');
        $myDiv.removeClass('processing');
    

提交回复
热议问题