编写jQuery选择器的最佳实践 [英] Best Practices For Writing jQuery Selectors

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

问题描述

我目前在我的jQuery代码中编写非常明确的选择器。例如,给定此标记



 < DIV类= codeblue > 
< div class =codeyellow>
< div class =codeorange>
< div class =codewhite>
< select id =codeChoice>
< option> red< / option>
< option> green< / option>
< option>黑色< / option>
< / select>
< / div>
< / div>
< / div>
< / div>

我使用这个显式选择器

  var $ select = $('。codeblue .codeyellow .codeorange .codewhite #codeChoice'); 

这样做会更好吗?

  var $ codeBlue = $('。codeblue'); 
var $ select = $ codeBlue.find('#codeChoice');

有没有使用显式选择器的性能命中?

当您的第一个选择器包括4个类别(=慢速检测)和1个ID(=更快检测)和第二个选择器1个类别(=慢速检测)和1个Id(=更快检测)时,第二个选择器将更快。



通常,选择器会更快,因为包含的件数更少。


I'm currently writing very explicit selectors in my jQuery code. For example given this markup

<div class="codeblue">
    <div class="codeyellow">
        <div class="codeorange">
            <div class="codewhite">
                <select id="codeChoice">
                    <option>red</option>
                    <option>green</option>
                    <option>black</option>
                </select>
            </div>
        </div>
    </div>
</div>

I use this explicit selector

var $select = $('.codeblue .codeyellow .codeorange .codewhite #codeChoice');

Would it be better to do this instead?

var $codeBlue = $('.codeblue');
var $select = $codeBlue.find('#codeChoice');

Are there any performance hits for not using explicit selectors?

解决方案

If you use concrete IDs, jQuery will be faster because it uses the native method document.getElementById(); As your first selector includes 4 Classes ( = Slow Detection ) and 1 id (= Faster Detection) and your second selector 1 Class ( = Slow Detection) and 1 Id ( = Faster Detection) , the second will be faster.

Generally selectors will be faster as less pieces are included.

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

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