选择器Sizzle
一)Sizzle( selector, context, results, seed )
该函数用于查找与选择器表达式selector匹配的元素集合,是选择器引擎的入口。
var Sizzle = function( selector, context, results, seed ) {
selector: CSS选择器表达式
context: DOM元素或者文档对象,作为查找元素的上下文,用于限定查找范围。默认值是当前文档对象。
results: 可选的数组或者类数组,把查找到的元素添加到其中。
seed:可选的元素集合,从该集合中过滤出匹配选择器表达式的元素集合。
//修正results, context results = results || []; context = context || document; //备份上下文 var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; }
//定义局部变量 var m, set, checkSet, extra, ret, cur, pop, i, prune = true, contextXML = Sizzle.isXML( context ), parts = [], soFar = selector;
// Reset the position of the chunker regexp (start from head) do { chunker.exec( "" ); m = chunker.exec( soFar ); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m );
//如果存在位置伪类,则从左向右查找 if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context, seed ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set, seed ); } } }
/* * 在指定的上下文数组context下,查找与选择器表达式 * selector匹配的元素集合,并且支持位置伪类。selector * 由一个块间关系符和一个块表达式组成。 * */ var posProcess = function( selector, context, seed ) { var match, tmpSet = [], later = "", root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end //删除selector中所以的伪类,并累积在later中。 while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } //如果删除伪类的选择器表达式中只剩一个块间关系符,则追加一个通配符"*" selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet, seed ); } return Sizzle.filter( later, tmpSet ); };
原文地址:https://www.cnblogs.com/Shadowplay/p/9816329.html
时间: 2024-10-29 05:14:42