【问题标题】:Jquery traversing and using selectorsjquery遍历和使用选择器
【发布时间】:2013-05-30 07:25:47
【问题描述】:

我正在读一本书,他们展示了几个如何在 DOM 上选择元素的示例,但他们建议始终在选择器上使用 Jquery 遍历方法,例如,如果您在 div 中有一个列表而不是使用

$("#myList > li")

你应该使用

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

大多数时候我使用第一个而不是后者,作者说第二个更受欢迎且效率更高,但他没有说明原因,谁能解释这背后的原因?

【问题讨论】:

  • 如果你对性能感兴趣,你根本不应该使用 jQuery。使用你更清楚的东西。
  • jQuery selector performance 的可能重复项
  • Read thisChild and adjacent selectors are inefficient because, for each matching element, the browser has to evaluate another node. It becomes doubly expensive for each child selector in the rule. Again, the less specific the key, the greater the number of nodes that need to be evaluated. However, while inefficient, they are still preferable to descendant selectors in terms of performance.

标签: javascript jquery jquery-selectors


【解决方案1】:

我认为在特定情况下的性能差异归结为:

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

还有这里的性能测试:http://jsperf.com/ae-d2-56-2a-e2-36-a3-d3-52-74

jQuery 可能会在给定选择器的情况下检查它是否是 li,但这仍然会比 querySelectorAll 或 Sizzle 快。

【讨论】:

  • 有趣的是,在 Opera 中,原生选择器的速度大约快了 50% :-)
  • jsperf 不是苹果对苹果,因为它没有按标签名称过滤子项。这样做,事实证明querySelectorAll 是最快的。请参阅修改后的 jsperf。
  • 修改后的 jsperf 位于 jsperf.com/ae-d2-56-2a-e2-36-a3-d3-52-74/3。 FWIW,事实证明 XPath (document.evaluate) 比 querySelectorAll 慢五倍左右。
  • @torazaburo:这很有趣。无论如何,所有这些性能测试通常都是无关紧要的,这里不必担心性能损失,我只是想说明一下差异。
猜你喜欢
  • 1970-01-01
  • 2013-10-23
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
  • 2015-01-03
  • 2011-06-11
  • 2013-02-19
  • 1970-01-01
相关资源
最近更新 更多