jQuery优化选择器 [英] jQuery optimization selector

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

问题描述

我想知道是否有一天在jQuery中输入选择器时,如果您将选择器指定得非常具体或过于宽松,会在性能上有所不同.

I was wondering the other day when typing you selectors in jQuery would it make a difference in performance if you specify your selectors very specific or very loosely.

例如

$('$myId .someElement')

$('table#myId > tbody > tr > td > div.someElement');

第二个选项会快很多还是差异可以忽略不计,例如,如果需要一遍又一遍地查找相同的元素,请执行.each().

Would the 2nd option be a lot quicker or would the difference be neglectable, say when doing .each() if you need to find the same element over and over.

推荐答案

我会去:

$('.someElement', '#myId')

由于getElementById是最快的选择器操作,因此您首先要过滤内容,然后搜索类.选择器越少,选择速度就越快(取决于使用后代还是 child 选择器-检查注释!). 基于@Felix测试用例的测试.

Since getElementById is the fastest selector operation, you are first filtering your content and then searching for the class. Also the fewer the selectors the faster the selections will be (depends if using descendant or child selectors - check comments!) . Test based on @Felix test case.

因此可以增强此答案.基于jQuery 文档:

so to enhance this answer. Based on the jQuery documentation:

默认情况下,选择器执行其 从DOM开始的DOM搜索 文档根目录.但是, 可以为 通过使用可选的第二个进行搜索 $()函数的参数.

By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function.

因此,当您提供第二个参数(上下文)时,jQuery将首先搜索该 元素,然后在其中进行搜索,因此可以将其翻译为:

So when you provide a second parameter (a context), jQuery will search for that element first and then search within it, so it would be translated from:

$('.someElement', '#myId')

收件人:

$('#myId').find('.someElement')

现在的诀窍是,由于ID选择是 最快 context . > .现在您会说,为什么不使用第二个已经翻译过的语言,因为我实际上并不在乎,因为第一个语言更干净而且速度也不慢:

Now the trick is, trying to find the closest container of your element that actually holds an ID and put it as context, since ID selection is the fastest. Now you would say, why not then using the second already translated one, by I wouldn't actually care that much since the first is cleaner and it's not much slower:

                    $('.someElement', '#myId')                  $('#myId').find('.someElement')
Chrome 8.0.552              36,527                                      37,400
Firefox 3.6.13              17,632                                      19,155

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

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