jQuery selector re-use best practice

2019-02-28 03:01发布

问题:

When storing a DOM object as a variable, which is the best practice use of that variable:

// Option 1

var myElement1 = $(".container").find('ul li:eq(1)');
$(myElement1).css('background', 'red');


// Option 2

var myElement2 = $(".container").find('ul li:eq(2)');
myElement2.css('background', 'blue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="container">
  <ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
   </ul>
 </div>

It seems like I have seen it both ways, and as you can see, they both do the job. Options 1 seems a little redundant to me, but I just wanted to check before committing Option 2 to my personal style.

回答1:

The second option is completely valid and good practice, however the first makes no sense. You're trying to jQueryify an object which has already been jQueryified. It basically is something like $($("body")).

Also note that it's good practice to prepend $ to variables which contains jQuery object. Your code should look like this:

var $myElement2 = $(".container").find('ul li:eq(2)');
$myElement2.css('background', 'blue');

As @Terry wrote, the most optimized way would be:

var $c = $(".container ul li");
var $second = $c.eq(2);


回答2:

You are right, the first case is redundant, and actually takes longer to execute (albeit not by a whole lot)

You can see this in the snippet here:

var s = window.performance.now();

var myElement1 = $(".container").find('ul li:eq(1)');
$(myElement1).css('background', 'red');

var e = window.performance.now();
console.log(e - s);

s = window.performance.now();

var myElement2 = $(".container").find('ul li:eq(2)');
myElement2.css('background', 'blue');

e = window.performance.now();
console.log(e - s);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
  </ul>
</div>

It's giving me about a 2 to 3 millisecond difference in speed.

I'd stick with the second option as it's cleaner and faster.