Most efficient way to re-use jQuery-selected elements

后端 未结 4 2288
南方客
南方客 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');
    
    0 讨论(0)
  • 2021-02-20 17:28

    This also holds for applying the jQuery function to elements returned in an event handler. Try to avoid applying $(...) too many times, because this is slow. Instead create a variable that contains the result of $(...). Good practice is to start the variable with a $, which gives a hint about the jQuery object inside the variable.

    $('a').click(function(){
      var $this = $(this);
      $this.addClass("clicked");
      $this.attr("clicked", true);
    });
    
    0 讨论(0)
  • 2021-02-20 17:29

    if you're using jQuery selector (like $('#element')), then yes, you should always store your results.

    if you're using object and wrapping it in jQuery (like $(this)), it's not necessary, because jQuery doesn't need to search for that element again.

    0 讨论(0)
  • 2021-02-20 17:40

    You should write your code such that you limit the number of DOM traversals.

    When you write something like this:

    $('#my_div').css('background','red');
    //some other code
    $('#my_div').attr('name','Red Div');
    

    You are finding #my_div twice, which is inefficient.

    You can improve this either by assigning the result of a selector (i.e. var x = $('.something')) and manipulate the variable x, or you can chain your method calls like this:

    $('#my_div').css('background','red').attr('name','Red Div');
    

    You'll see the above code used a lot, because you're finding the element once. The css() method will apply a CSS style and return the actual result of $('#my_div'), so you can invoke another method, in this case attr().

    My preferred way of handling the re-use of selectors is to store them as a variable, and wrap my stuff in a closure.

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