编写jQuery选择器的最佳实践 [英] Best Practices For Writing jQuery Selectors
问题描述
我目前在我的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');
有没有使用显式选择器的性能命中?
通常,选择器会更快,因为包含的件数更少。
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屋!