jQuery源码分析之select()方法

快乐打工仔 分类:实例代码

本章节对jQuery源码中的select()实现进行一下分析。

分析文本在源码中,以注释的形式存在,感兴趣的朋友可以做一下参考。

代码如下:

/*
 * select方法是Sizzle选择器包的核心方法之一,其主要完成下列任务:
 * 1、调用tokenize方法完成对选择器的解析
 * 2、对于没有初始集合(即seed没有赋值)且是单一块选择器(即选择器字符串中没有逗号),
 *  完成下列事项:
 *  1) 对于首选择器是ID类型且context是document的,则直接获取对象替代传入的context对象
 *  2) 若选择器是单一选择器,且是id、class、tag类型的,则直接获取并返回匹配的DOM元素
 *  3) 获取最后一个id、class、tag类型选择器的匹配DOM元素赋值给初始集合(即seed变量)
 * 3、通过调用compile方法获取“预编译”代码并执行,获取并返回匹配的DOM元素
 * 
 * @param selector 已去掉头尾空白的选择器字符串
 * @param context 执行匹配的最初的上下文(即DOM元素集合)。若context没有赋值,则取document。
 * @param results 已匹配出的部分最终结果。若results没有赋值,则赋予空数组。
 * @param seed 初始集合
 */
function select(selector, context, results, seed) {
      
    var i, tokens, token, type, find, 
    // 调用tokenize函数解析selector
    match = tokenize(selector);
  
    // 若没有提供初始集合
    if (!seed) {
        // Try to minimize operations if there is only one group
        // 若只有一组选择器,即选择器字符串没有逗号
        if (match.length === 1) {
            // Take a shortcut and set the context if the root selector
            // is an ID
            /*
             * 下面代码是用来处理根选择器是ID类型的快捷方式
             * 
             * 在此使用slice[0]来创建一个新的集合,
             * 确保原有的集合不会被之后代码变更掉
             */
            tokens = match[0] = match[0].slice(0);
            /*
             * 若选择器是以id类型开始,且第二个是关系符(即+~>或空格),
             * 则获取id所属对象作为context继续完成后续的匹配
             * 
             * 此处的条件判断依次为:
             * tokens.length > 2 :若tokens有两个以上的选择器
             * (token = tokens[0]).type === "ID" :第一个选择器的类型为ID(即以#开头的),
             * support.getById :支持getElementById函数
             * context.nodeType === 9 :context对象是document
             * documentIsHTML :当前处理的是HTML代码
             * Expr.relative[tokens[1].type] :第二个tokens元素是一个关系(即+~>或空格)
             * 在满足上面所有条件的情况下,执行if内的语句体
             */
            if (tokens.length > 2 && (token = tokens[0]).type === "ID"
                    && support.getById && context.nodeType === 9
                    && documentIsHTML && Expr.relative[tokens[1].type]) {
  
                // 将当前上下文指向第一个ID选择器指定的节点对象
                context = (Expr.find["ID"](token.matches[0].replace(
                        runescape, funescape), context) || [])[0];
                  
                // 若当前上下文内没有指定ID对象,则直接返回results
                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
             *      + "*[>+~]|<img src="static/image/smiley/default/sad.gif" smilieid="2" border="0" alt="">even|odd|eq|gt|lt|nth|first|last)(?:\("
             *      + whitespace + "*((?:-\d)?\d*)" + whitespace
             *      + "*\)|)(?=[^-]|$)", "i")
             * needsContext用来匹配选择器字符串中是否包含下列内容:
             * 1、>+~三种关系符
             * 2、:even、<img src="static/image/smiley/default/shocked.gif" smilieid="6" border="0" alt="">dd、: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));
    return results;
}

回复

我来回复
  • 暂无回复内容