jQuery选择器重用最佳实践 [英] jQuery selector re-use best practice

查看:68
本文介绍了jQuery选择器重用最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将DOM对象存储为变量时,这是该变量的最佳实践:

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>

似乎我已经同时看到了这两种方式,并且正如您所看到的,它们都可以完成任务.选项1对我来说似乎有点多余,但是我只想检查一下,然后再将选项2更改为我的个人风格.

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.

推荐答案

第二个选项完全有效并且是很好的做法,但是第一个没有意义.您正在尝试jQueryify一个已经被jQuery化的对象.基本上就像$($("body")).

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")).

还请注意,在$之前添加包含jQuery对象的变量是一种很好的做法.您的代码应如下所示:

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');

正如@Terry所写,最优化的方法是:

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

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

这篇关于jQuery选择器重用最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆