XPath 还是 querySelector?

XPath 可以做所有 querySelector 可以做的事情,甚至更多,那么你什么时候会选择后者呢?我还没有看到任何速度基准比较这两者,所以现在我根据语法简洁性进行选择,这似乎有点随意.

XPath can do everything querySelector can do, and more, so when would you ever choose the latter? I haven't seen any speed benchmarks comparing the two, so right now I'm choosing based on syntax conciseness, which seems kind of arbitrary.

我可能应该说我正在为 Firefox 编写 Greasemonkey 脚本,所以我不担心跨浏览器的兼容性,并且宁愿不包含任何库.

I probably should have stated that I'm writing Greasemonkey scripts for Firefox, so I'm not worried about cross-browser compatibility, and would rather not include any libraries.

推荐答案

你用的是什么浏览器?在 Safari(或 iPhone)中,querySelector 和 querySelectorAll 比 XPath 快得多.IE 根本不支持 XPath,IE6 和 IE7 也不支持 querySelector.最快的跨浏览器选择器引擎是由 John Resig 创建的 Sizzle.Sizzle 也是 jQuery 中使用的主要选择器引擎.它在适当的地方使用 querySelector,在 querySelector 不可用的地方使用普通的 DOM 方法.

What browser are you using? In Safari (or the iPhone), querySelector and querySelectorAll are much faster than XPath. IE doesn't support XPath at all, and IE6 and IE7 don't support querySelector. The fastest cross-browser selector engine is Sizzle, created by John Resig. Sizzle is also the main selector engine used in jQuery. It uses querySelector where appropriate and normal DOM methods where querySelector is unavailable.

相关文章