【发布时间】:2011-08-16 22:58:14
【问题描述】:
我想知道在使用 jQuery 进行选择时使用 context 参数与使用普通的 CSS 范围选择器相比是否有任何优势。
假设我有这个 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 中获取所有新联系人(由“新”类标记),哪种方法更快、扩展性更好等等?
$('.contacts .new');
或者
$('.new', '.contacts');
更新
答案和 cmets 中散布着很多很棒的信息。总结要点,在大多数浏览器中,当有多个 .contacts div 时,单个选择器的伸缩性更好。在大多数浏览器中,两个选择器上下文方法更快,只有一个 .contacts div 存在。
值得一提的是,我们可以使用一种方法在带有 id 的元素中进行选择。
$('p:first', '#chapter2'); // get the first paragraph from chapter 2
对于我们从可能很大的一组元素中进行选择的实例,请使用单一选择器方法。
$('.chapter p:first-child'); // get the first paragraph from all chapters
【问题讨论】:
-
您在测试它们时发现了什么?
-
有时询问更容易,您最终会获得更多信息。例如,在这里我了解到 jsperf 存在。 :)
标签: jquery performance