哪种jQuery选择方法更快? [英] Which jQuery selection method is faster?

查看:59
本文介绍了哪种jQuery选择方法更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道使用jQuery与普通的CSS作用域选择器进行选择时,使用context参数是否有任何优势.

I'm wondering if there's any advantage to using the context parameter when making selections with jQuery versus using a normal CSS scoped selector.

假设我有这个html:

Assuming I have this html:

<div class="contacts">
    <h1>All contacts</h1>
    <div class="contact new">
        <p class="name">Jim Jones</p>
        <p class="phone">(555) 555-1212</p>
    </div>
    <div class="contact new">
        <p class="name">Bob Smith</p>
        <p class="phone">(555) 555-1213</p>
    </div>
    <div class="contact new">
        <p class="name">Dave Baker</p>
        <p class="phone">(555) 555-1214</p>
    </div>
    <div class="contact">
        <p class="name">Pete Harrison</p>
        <p class="phone">(555) 555-1215</p>
    </div>
    <div class="contact">
        <p class="name">George Donald</p>
        <p class="phone">(555) 555-1216</p>
    </div>
    <div class="contact">
        <p class="name">Chris Root</p>
        <p class="phone">(555) 555-1217</p>
    </div>
</div>

如果我想从通讯录div中获取所有新的通讯录(以"new"类标记),哪种方法更快,扩展性更好等等??

If I want to grab all new contacts (marked by 'new' class) from the contacts div, which method is faster, scales better, etc..?

$('.contacts .new');

$('.new', '.contacts');

jsFiddle

更新

答案和评论中散布着许多重要信息.总结要点,在大多数浏览器中,当有多个.contact div时,单个选择器可以更好地缩放.在大多数浏览器中,只有一个.contacts div时,两个选择器上下文方法更快.

There's a lot of great info strewn throughout the answers and comments. To summarize the major points, in most browsers a single selector scales better when there are multiple .contacts divs. The two selector context method is faster, in most browsers, with only a single .contacts div present.

对此有用的东西是,当在具有id的元素内部进行选择时,可以使用一种方法.

Something useful to take away from that is we can use one method when selecting inside an element with an id.

$('p:first', '#chapter2'); // get the first paragraph from chapter 2

对于要从一组可能很大的元素中进行选择的实例,请使用单一选择器方法.

And use the single selector method for instances where we're selecting from a potentially large group of elements.

$('.chapter p:first-child'); // get the first paragraph from all chapters

推荐答案

针对所有(我)赔率,似乎2号是最快的.

Against all (my) odds, seems number 2 is the fastest.

此处查看

这篇关于哪种jQuery选择方法更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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