if (!context) {
return results;
}
// 选择器字符串去掉第一个ID选择器
selector = selector.slice(tokens.shift().value.length);
}
// Fetch a seed set for right-to-left matching
/*
* 下面while循环的作用是用来根据最后一个id、class、tag类型的选择器获取初始集合
* 举个简单例子:若选择器是"div[title='2']",
* 代码根据div获取出所有的context下的div节点,并把这个集合赋给seed变量,
* 然后在调用compile函数,产生预编译代码,
* 预编译代码完成在上述初始集合中执行[title='2']的匹配
*
* 首先,检查选择器字符串中是否存在与needsContext正则表达式相匹配的字符
* 若没有,则将依据选择器从右到左过滤DOM节点
* 否则,将先生成预编译代码后执行(调用compile方法)。
*/
/*
* "needsContext" : new RegExp("^" + whitespace
*+ "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:("
*+ whitespace + "*((?:-d)?d*)" + whitespace
*+ "*)|)(?=[^-]|$)", "i")
* needsContext用来匹配选择器字符串中是否包含下列内容:
* 1、>+~三种关系符
* 2、:even、:odd、:eq、:gt、:lt、:nth、:first、:last八种伪类
* 其中,(?=[^-]|$)用来过滤掉类似于:first-child等带中杠的且以上述八个单词开头的其它选择器
*/
i = matchExpr["needsContext"].test(selector) ? 0
: tokens.length;
while (i--) {
token = tokens[i];
// Abort if we hit a combinator
// 遇到关系符跳出循环
if (Expr.relative[(type = token.type)]) {
break;
}
if ((find = Expr.find[type])) {
// Search, expanding context for leading sibling
// combinators
/*
* rsibling = new RegExp(whitespace + "*[+~]")
* rsibling用于判定token选择器是否是兄弟关系符
*/
if ((seed = find(token.matches[0].replace(
runescape, funescape), rsibling
.test(tokens[0].type)
&& context.parentNode || context))) {
// If seed is empty or no tokens remain, we can
// return early
// 剔除刚用过的选择器
tokens.splice(i, 1);
selector = seed.length && toSelector(tokens);
/*
* 若selector为空,说明选择器仅为单一id、class、tag类型的,
* 故直接返回获取的结果,否则,在获取seed的基础上继续匹配
*/
if (!selector) {
push.apply(results, seed);
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the
// selector above
/*
* 先执行compile(selector, match),它会返回一个“预编译”函数,
* 然后调用该函数获取最后匹配结果
*/
compile(selector, match)(seed, context, !documentIsHTML, results,
rsibling.test(selector));










