具有ID的jQuery选择器的性能 [英] Performance of jQuery Selectors with ID
问题描述
我知道在jQuery中如果我们使用 ID
来选择元素,那就非常有效。我对这个选择器有疑问:
I know in jQuery if we use ID
to select elements,it's so efficient.I have a question about this selectors:
请考虑以下3个选择器:
please consider this 3 selectors:
$('#MyElement')
$('#Mytbl #MyElement')
$('#Mytbl .MyClass')
哪一个更快,为什么?我如何检查在jQuery中选择元素所用的时间?
which one is faster and why?How I can check the time elapsed to select my element in jQuery?
推荐答案
直接ID选择器总是是最快的。
A direct ID selector will always be the fastest.
我根据你的问题创建了一个简单的测试用例...
I've created a simple test case based on your question...
http:// jsperf.com/selector-test-id-id-id-id-class
选择嵌套ID是错误的,因为如果ID是唯一的( 应该是什么),然后它是否嵌套并不重要。
Selecting nested ID's is just wrong, because if an ID is unique (which it should be), then it doesn't matter if it's nested or not.
这篇关于具有ID的jQuery选择器的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!