何时使用 querySelectorAll
在我写的一段示例代码中
var as = toArray(document.getElementsByClassName("false")).filter(function (el) {
return el.tagName === "A";
});
我想我可以用
var as = document.querySelectorAll("a.false");
替换它现在阅读以下事实后
- 假装浏览器支持不支持一个问题(我们有垫片和填充)。
- 假装您不采用通用 jQuery 思维方式,您应该使用 QSA 来获取每个元素。
- 我将编写
qsa
而不是document.querySelectorAll
因为我很懒。
问题:什么时候我应该采用 QSA 而不是普通方法?
很明显,如果您执行 qsa("a")
或 qsa(".class")
或 qsa("#id")
您的这样做是错误的,因为有更好的方法(byTagName、byClassName、byId)。
很明显,qsa("div > p.magic")
是一个明智的用例。
问题:但是 qsa("tagName.class")
是 QSA 的一个很好的用例吗?
顺便说一句,还有一些名为 NodeIterator
我问了一个关于 QSA 与 NodeIterator 的问题
In a piece of example code I wrote
var as = toArray(document.getElementsByClassName("false")).filter(function (el) {
return el.tagName === "A";
});
And I was thinking I could replace that with
var as = document.querySelectorAll("a.false");
Now after reading the following facts
- Pretend browser support isn't an issue (we have shims and polyfills).
- Pretend your not in your generic jQuery mindset of you shall use QSA for getting every element.
- I'm going to write
qsa
instead ofdocument.querySelectorAll
because I'm lazy.
Question: When should I favour QSA over the normal methods?
It's clear that if your doing qsa("a")
or qsa(".class")
or qsa("#id")
your doing it wrong because there are methods (byTagName, byClassName, byId) that are better.
It's also clear that qsa("div > p.magic")
is a sensible use-case.
Question: But is qsa("tagName.class")
a good use-case of QSA?
As a futher aside there are also these things called NodeIterator
I've asked a question about QSA vs NodeIterator
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当 gEBI、gEBN、gEBCN 由于选择器复杂而不起作用时,您应该使用 QSA。
QSA 与 DOM 解析取决于偏好以及您将如何处理返回的数据集。
You should use QSA when the gEBI, gEBN, gEBCN do not work because your selector is complex.
QSA vs DOM parsing is a matter of preference and what your going to be doing with the returned data set.
如果浏览器支持不是问题,我会在任何地方使用它。如果您只能使用一种方法,为什么还要使用 4 种不同的方法(...byId、...byTagName、...byClassName)。
QSA 似乎较慢(...byId),但仍然只需要几毫秒或更短的时间。大多数时候你只调用它几次,所以不是问题。当您遇到速度瓶颈时,您始终可以用适当的其他方法替换 QSA。
If browser support was not an issue I would just use it everywhere. Why use 4 different methods (...byId, ...byTagName, ...byClassName) if you could just use one.
QSA seems to be slower (...byId), but still only takes a few miliseconds or less. Most of the times you only call it a few times, so not a problem. When you hit a speed bottleneck you could always replace QSA with the appropriate other one.
我已经设置了一些测试供你尝试。看起来 QSA 慢很多。但如果你不那么频繁地调用它,那应该不成问题。
http://jsfiddle.net/mxZq3/
编辑 - jsperf 版本
http://jsperf.com/qsa-vs-regular-js
I've set up some tests for you to mess around with. It appears that QSA is a lot slower. But if you are not calling it that much, it shouldn't be a problem.
http://jsfiddle.net/mxZq3/
EDIT - jsperf version
http://jsperf.com/qsa-vs-regular-js