现在的位置: 首页 > 综合 > 正文

$(“.class”)后到底发生了什么 — jquery选择器分析

2012年05月25日 ⁄ 综合 ⁄ 共 1637字 ⁄ 字号 评论关闭
$(".class")到底发生了什么。让我们一步一步来看

 

var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
},

看看jQuery.fn.init( selector, context )
注意这里的context是undefined
它首先处理$(""), $(null), or $(undefined),接着看是不是selector是不是selectorDOMElement,或者body(因为只有一个需要对其优化)
接着就到了我们的要去的地方
// Handle HTML strings
if ( typeof selector === "string" ) {
  // Are we dealing with HTML string or an ID?
  match = quickExpr.exec( selector );
if ( match && (match[1] || !context) ) {
quickExpr这个的值是/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,
简单解释一下就是$("<span>")或者是$("#id"),显然是不符合要求的。
else if ( !context && !rnonword.test( selector ) ) {
rnonword这个的值是/\W/,这是个用来匹配$("span")这种的,显然又不符合
else if ( !context || context.jquery ) {
return (context || rootjQuery).find( selector );
注意rootjQuery其实就是$(document),绕了半天$(".class")就是$(document).find(".class")。接着看

 

find: function( selector ) {
jQuery.find( selector, this[i], ret );
注意下面这行代码
jQuery.find = Sizzle;
也就是说jQuery.find默认是由Sizzle引擎提供的。

那么开始进入Sizzle的代码了。
先从简单的说起

if ( document.querySelectorAll ) {
Sizzle = function(query, context, extra, seed){
好的,这就很明白了,如果你的浏览器支持document.querySelectorAll,那么jQuery就直接用document.querySelectorAll来做了。
有点区别的是IE8需要在document上设个id(如果没有设Sizzle设置的id是__sizzle__),使用类似这样的查询context.querySelectorAll( "#__sizzle__ .class")

不支持document.querySelectorAll的IE6、IE7我们接着看

var Sizzle = function(selector, context, results, seed) {
首先用chunker将selector拆分放到parts数组中,因为我们这里就只有.class,所以parts数组只有一个".class"
if ( parts.length > 1 && origPOS.exec( selector ) ) {
origPOS是用来解析$("span:first"),有个nth|eq|gt|lt|first|last|even|odd这几种情况的,显然.class是不符合的,到3014行的else

未完待续

 

 

抱歉!评论已关闭.