首先使用:优化jQuery选择器 [英] Optimize jQuery selector with :first
问题描述
我有这样的感觉 $('。class:first')
比 $('。class')$运行得更快C $ C>。所以,只要我知道子集中只有一个
.class
,我就用它了。
I have had this feeling that $('.class:first')
runs faster than $('.class')
. So anytime I know there only is one .class
in the subset, I've used it.
:首先
让查询运行得更快,还是不必要?
Does :first
make the query run faster, or is it unnecessary?
推荐答案
它实际上取决于浏览器, :first
不是CSS选择器,它是一个jQuery过滤器 - 因此需要一些额外的解析工作......其中 .class
本身可以传递给本机浏览器选择器方法(例如 document.querySelectorAll()
这里)。
It actually depends on the browser, :first
isn't a CSS selector, it's a jQuery filter - so that requires some extra parsing work...where as .class
by itself can be handed off to a native browser selector method (e.g. document.querySelectorAll()
here).
其中任何一个实际上都会更快:
Any of these would actually be faster:
$('.class').first()
//or...
$('.class').eq(0)
//or fastest:
$('.class').slice(0, 1)
...因为他们运行本机代码然后只是取该集合中的第一个条目。
...since they run native code then just take the first entry in that set.
这篇关于首先使用:优化jQuery选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!