简体   繁体   English

jQuery遍历和使用选择器

[英]Jquery traversing and using selectors

I'm reading a book and they show a couple of examples of how to select elements on the DOM, but they advise to always use Jquery trasversing methods over the selectors, for example if you have a list inside a div instead of using 我正在读一本书,其中显示了一些有关如何在DOM上选择元素的示例,但它们建议始终在选择器上使用Jquery遍历方法,例如,如果在div中有一个列表而不是使用

$("#myList > li")

You should use 你应该用

$("#myList").children("li")

Most of the time I use the first over the latter, the author says the 2nd is prefered and more efficient but he does not address why, can anyone explain the reason behind this? 在大多数情况下,我使用第一个而不是第二个,作者说第二个是更可取的,并且效率更高,但是他没有说明原因,有人可以解释这背后的原因吗?

I think the difference in performance in that particular case comes down to this: 我认为在特定情况下性能的差异归结为:

document.querySelectorAll('#myList > li');
// VS
document.getElementById('myList').children;

And the performance test here: http://jsperf.com/ae-d2-56-2a-e2-36-a3-d3-52-74 以及此处的性能测试: http : //jsperf.com/ae-d2-56-2a-e2-36-a3-d3-52-74

jQuery might check to see if it's a li given the selector but that's still going to be faster than querySelectorAll or Sizzle. jQuery可能会检查给定的选择器是否为li ,但它仍会比querySelectorAll或Sizzle更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM