Is it possible to use multiple variables instead of selectors in jQuery

前端 未结 9 2451
半阙折子戏
半阙折子戏 2020-12-07 20:03

I know that it\'s faster to do the following:

var $header = $(\"#header\");
$header.css({color:\"#ff0000\"});
$header.find(\"a\").addClass(\"foo\");
<         


        
9条回答
  •  攒了一身酷
    2020-12-07 20:49

    I found the solutions a few minutes after posting this. For those who are wondering, here it is:

    $.merge($header_elements, $footer_elements).css({color:"#ff0000"});
    

    Is it faster? I don't know yet, I'll need to run some tests to find out.

    EDIT:

    I tested it with JS Fiddle here : http://jsfiddle.net/bgLfz/1/

    I tested using selector each time, variable for both selector, variables with $.merge() and using .add(). Each test was run 1000 times.

    Results on my side are as follow (from faster to slower):

    1. Using $.merge() (average of 7ms)
    2. Using both variable one after the other (average of 10ms but the code needs to be duplicated)
    3. Using .add() (average of 16ms)
    4. Using selectors each time (average of 295ms)

提交回复
热议问题