通过 id - #id 或 span#id 获取元素的更有效方法是什么?为什么?
通过 id 获取元素的更有效方法是什么(如果它的 id 是唯一的)?
#id
或者
#div1 #id
或者
span#id
为什么?
您能告诉我在哪里可以读到此类内容吗? (如何更快、更有效地使用 jQuery 选择器以及为什么要这样)
谢谢!
What is more effective way to get an element by id (if its id is unique)?
#id
or
#div1 #id
or
span#id
and why?
Could you please tell me where I can read about such things?
(How to use jQuery selectors faster and more effectively and why exactly so)
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
#id
// 在 jQuery 中通过 ID 获取元素的最有效方法HTML 元素的 id 应该是唯一的,因此 jQuery 将使用
document.getElementById() 而不是
document.getElementsByTagName()
并迭代元素数组来搜索正确的元素。#id
// most efficient way to get an element by Id in jQueryid's of HTML elements are suppose to be unique and because of this jQuery will make use of
document.getElementById()
instead ofdocument.getElementsByTagName()
and iterate though the array of elements searching for the correct one.为什么?因为它不会考虑其他条件,并且在任何情况下,
#id
应该只是一个,因此(在很多情况下)使用span#id 没有意义
Why? Because it doesn't look on another conditions, and in any case,
#id
should be only one so it doesn't make (in a lot of cases) sense to usespan#id
仅 id 更好,因为代码必须查找单个元素。
请参阅此测试来证明它http://jsperf.com/id-vs-tag- id
Just the id is better simply because the code have to look for a single element.
See this test that proove it http://jsperf.com/id-vs-tag-id
CSS 选择器(以及 Sizzle,jQuery 中执行查询工作的东西)从
从右到左
工作,知道这一点,您就可以轻松地自己回答问题。仅查询
#id
始终是最快的解决方案。不仅因为之后会先查询更多语句,而且 jQuery 还为您优化了这种情况。这意味着,只需使用像#id
这样的选择器就可以直接调用.getElementById()
,这只是获取元素引用最快的 DOM 操作。然而,在其他情况下,不要过于明确也会更快。那是因为从右到左的事情。
CSS selectors (aswell as Sizzle, the thing within jQuery which does the query job) work from
right to left
knowing that, you can easily answer the question yourself. Just querying for
#id
is always the fastest solution. Not only for the reason that more statements after that would be queried first, but also jQuery optimizes this case away for you. That means, just having a selector like#id
would directly invoke.getElementById()
, which is just the fastest possible DOM operation to get a reference to an element.However, it's also faster not to be overexplicit in other cases. Thats because of the right to left thing.
使用 jQuery,很容易只使用
$("#theId")
因为它寻找的只是唯一的 id,而不是寻找其他条件,例如父 idWith jQuery its very easy to just use
$("#theId")
cause all its looking for is the unique id rather than looking for other conditions such as a parent id#id
是最快的,因为它是唯一的。我不知道您可以在哪里阅读此内容,但这里有一个页面,您可以在其中测试和基准选择器:
基准选择器
#id
is the fastest, because it is unique.I don't know where you can read up on this, but here is a page where you can test and benchmark selectors:
Benchmark selectors