简体   繁体   English

jQuery选择器重用最佳实践

[英]jQuery selector re-use best practice

When storing a DOM object as a variable, which is the best practice use of that variable: 将DOM对象存储为变量时,这是该变量的最佳实践:

 // 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对我来说似乎有些多余,但是我只想在将选项2更改为我的个人风格之前进行检查。

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. 您正在尝试使用jQueryify一个已经被jQuery化的对象。 It basically is something like $($("body")) . 基本上,它类似于$($("body"))

Also note that it's good practice to prepend $ to variables which contains jQuery object. 还要注意,将$放在包含jQuery对象的变量之前是一个好习惯。 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: 正如@Terry所写,最优化的方式是:

var $c = $(".container ul li");
var $second = $c.eq(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. 这给了我大约2到3毫秒的速度差。

I'd stick with the second option as it's cleaner and faster. 我坚持使用第二个选项,因为它更干净,更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM