问题描述
我希望在选择<input type="text" id="txtID" class="txtClass"/>
元素时,$('#childDiv2 .txtClass')
或$('#childDiv2 input.txtClass')
的性能更好.但是根据此性能分析 $('.txtClass');
是其中最好的选择器.我正在使用JQuery 1.7.2有人对此有解释吗?
I was hoping $('#childDiv2 .txtClass')
or $('#childDiv2 input.txtClass')
perform better when selecting <input type="text" id="txtID" class="txtClass"/>
element. But according to this performance analysis $('.txtClass');
is the best selector among this. I'm using JQuery 1.7.2Does anybody have explanation for this?
HTML
<div class="childDiv2">
<input type="text" id="txtID" class="txtClass"/>
<p class="child">Blah Blah Blah</p>
</div>
JS
$('.txtClass');
$('#childDiv2 .txtClass')
$('#childDiv2 > .txtClass')
$('input.txtClass')
$('#childDiv2 input.txtClass')
推荐答案
现代浏览器公开了非常有效的 getElementsByClassName()方法,该方法返回具有给定类的元素.这就是为什么单个类选择器在您的情况下更快的原因.
Modern browsers expose a very efficient getElementsByClassName() method that returns the elements having a given class. That's why a single class selector is faster in your case.
详细说明您的示例:
$(".txtClass") => getElementsByClassName()
$("#childDiv2 .txtClass") => getElementById(),
then getElementsByClassName()
$("#childDiv2 > .txtClass") => getElementById(),
then iterate over children and check class
$("input.txtClass") => getElementsByTagName(),
then iterate over results and check class
$("#childDiv2 input.txtClass") => getElementById(),
then getElementsByTagName(),
then iterate over results and check class
如您所见,第一种形式在现代浏览器中是最快的,这是很合逻辑的.
As you can see, it's quite logical for the first form to be the fastest on modern browsers.
这篇关于jQuery元素+类选择器性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!