jQuery元素+类选择器性能 [英] Jquery element+class selector performance

查看:81
本文介绍了jQuery元素+类选择器性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在选择<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.2 Does 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')

推荐答案

现代浏览器公开了非常有效的

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元素+类选择器性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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