想象一下这个简化的标记:
<div id="header">
<!-- Other things.... -->
<div id="detail">
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
并假设您已经拥有此代码:
var $hdr = $("#header");
Run Code Online (Sandbox Code Playgroud)
jQuery以这种方式查找"细节"是否有任何速度差异:
var $detail = $("#detail", $hdr);
Run Code Online (Sandbox Code Playgroud)
VS
var $detail = $("#detail");
Run Code Online (Sandbox Code Playgroud)
由于ID正在查找详细信息?
不,你不必那样做.由于id在文档中是唯一的,因此无需添加任何其他优化.
我会去
var $detail = $("#detail");
Run Code Online (Sandbox Code Playgroud)
不会.传递上下文实际上会让它变慢.来自jQuery的相关源代码在下面给出了解释.
这段代码基本上说:
这是剥离的来源..
init: function( selector, context ) {
...
if ( typeof selector === "string" ) {
...
// This gets ignored because we passed a context
// document.getElementById() isn't called directly
if ( match && (match[1] || !context) ) {
...
} else {
elem = document.getElementById( match[2] );
...
}
...
// Either this gets executed if a jQuery wrapped context was passed
} else if ( !context || context.jquery ) {
return (context || rootjQuery).find( selector );
}
// Or this gets executed, if a simple selector was passed as context
} else {
return jQuery( context ).find( selector );
}
...
}
Run Code Online (Sandbox Code Playgroud)
match是正则表达式的结果数组,用于确定选择器是HTML字符串还是id表达式.如果它是HTML字符串,则将填充匹配[1].如果它是一个id(#someId),那么match[2]将填充.