对于jquery的selector核心就是jquery.find方法,从github上可以看到有native和sizzle两种实现
首先分析下native实现,源码(jquery 2.1.0)selector-native之jQuery.find函数实现如下
find: function( selector, context, results, seed ) {
var elem, nodeType,
i = 0;
results = results || [];
context = context || document;
// Same basic safeguard as Sizzle
if ( !selector || typeof selector !== "string" ) {
return results;
}
// Early return if context is not an element or document
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( seed ) {
while ( (elem = seed[i++]) ) {
if ( jQuery.find.matchesSelector(elem, selector) ) {
results.push( elem );
}
}
} else {
jQuery.merge( results, context.querySelectorAll(selector) );
}
return results;
}其实核心就一句
context.querySelectorAll(selector)
换句话说selector的实现是基于querySelectorAll的。
注意到selector-native中一段注释
| /* | |
| * Optional (non-Sizzle) selector module for custom builds. | |
| * | |
| * Note that this DOES NOT SUPPORT many documented jQuery | |
| * features in exchange for its smaller size: | |
| * | |
| * Attribute not equal selector | |
| * Positional selectors (:first; :eq(n); :odd; etc.) | |
| * Type selectors (:input; :checkbox; :button; etc.) | |
| * State-based selectors (:animated; :visible; :hidden; etc.) | |
| * :has(selector) | |
| * :not(complex selector) | |
| * custom selectors via Sizzle extensions | |
| * Leading combinators (e.g., $collection.find("> *")) | |
| * Reliable functionality on XML fragments | |
| * Requiring all parts of a selector to match elements under context | |
| * (e.g., $div.find("div > *") now matches children of $div) | |
| * Matching against non-elements | |
| * Reliable sorting of disconnected nodes | |
| * querySelectorAll bug fixes (e.g., unreliable :focus on WebKit) | |
| * | |
| * If any of these are unacceptable tradeoffs, either use Sizzle or | |
| * customize this stub for the project's specific needs. | |
| */ |
再回到querySelectorAll,它是一个支持css selector 的函数,详见nodeselector
223

被折叠的 条评论
为什么被折叠?



