Most efficient way to re-use jQuery-selected elements

后端 未结 4 2292
南方客
南方客 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: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.

提交回复
热议问题