【发布时间】:2011-05-23 02:27:33
【问题描述】:
我知道$("#id") 更快,因为它映射到原生 javascript 方法。 $("body")也一样吗?
【问题讨论】:
标签: javascript jquery jquery-selectors sizzle
我知道$("#id") 更快,因为它映射到原生 javascript 方法。 $("body")也一样吗?
【问题讨论】:
标签: javascript jquery jquery-selectors sizzle
这是直接来自source (code):
if ( selector === "body" && !context && document.body ) {
this.context = document;
this[0] = document.body;
this.selector = "body";
this.length = 1;
return this;
}
对于正文以外的标签
如果你再深入一点,如果没有给出上下文,他们会使用getElementsByTagName。与使用 Sizzle 引擎相比,这将大大提高性能。
// HANDLE: $("TAG")
} else if ( !context && !rnonword.test( selector ) ) {
this.selector = selector;
this.context = document;
selector = document.getElementsByTagName( selector );
return jQuery.merge( this, selector );
// HANDLE: $(expr, $(...))
}
【讨论】:
<body> 存在(它将在 document.ready 上)。
if ( selector === "body" && !context && document.body ) { 是 true 如果没有给出上下文,那是使用的代码,而不是元素选择器分支。
不,它不使用 Sizzle,$("body") 有一个特殊的快捷方式,you can see the code here:
// The body element only exists once, optimize finding it
if ( selector === "body" && !context && document.body ) {
this.context = document;
this[0] = document.body;
this.selector = "body";
this.length = 1;
return this;
}
请注意,这与$(document.body) 不同完全,因为$("body") 的结果上下文是document,而$(document.body)(与任何其他DOM 节点一样)具有自身的上下文。
【讨论】:
querySelectorAll()。但要直接回答,$("body.class") 或任何变体 except $("body") 都没有经过特殊处理,因此会被转储到选择器引擎。