init: function( selector, context ) {
var match, elem, ret, doc;
// 处理空白字符串,null,undefined参数
if ( !selector ) {
return this;
}
// 处理节点参数
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// 处理body参数(新增)
if ( selector === "body" && !context ) {
this.context = document;
this[0] = document.body;
this.selector = "body";
this.length = 1;
return this;
}
// 处理字符串参数,分七种情形:
//①单个标签,带对象属性包 ---> jQuery.merge
//②单个标签,不带对象属性包 ---> attr + jQuery.merge
//③复杂的HTML片断 ---> buildFragment + jQuery.merge
//④ID选择器,与找到的元素的ID不同 ---> getElementById + Sizzle + pushStack
//⑤ID选择器,与找到的元素的ID相同 ---> getElementById + 简单属性添加
//⑥标签选择器 ---> getElementsByTagName + jQuery.merge
//⑦其他CSS表达式 ---> Sizzle + pushStack
if ( typeof selector === "string" ) {
match = quickExpr.exec( selector );
if ( match && (match[1] || !context) ) {
if ( match[1] ) {
doc = (context ? context.ownerDocument || context : document);
ret = rsingleTag.exec( selector );
if ( ret ) {
if ( jQuery.isPlainObject( context ) ) {
selector = [ document.createElement( ret[1] ) ];
jQuery.fn.attr.call( selector, context, true );
} else {
selector = [ doc.createElement( ret[1] ) ];
}
} else {
ret = buildFragment( [ match[1] ], [ doc ] );
selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes;
}
return jQuery.merge( this, selector );
} else {
elem = document.getElementById( match[2] );
if ( elem ) {
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
} else if ( !context && /^\w+$/.test( selector ) ) {
this.selector = selector;
this.context = document;
selector = document.getElementsByTagName( selector );
return jQuery.merge( this, selector );
} else if ( !context || context.jquery ) {
return (context || rootjQuery).find( selector );
} else {
return jQuery( context ).find( selector );
}
// 处理函数参数,直接domReady
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
//处理jQuery对象参数
if (selector.selector !== undefined) {
this.selector = selector.selector;
this.context = selector.context;
}
//无论是数组还是类数组(如NodeList),统统使用jQuery.makeArray来为实例添加新的元素
return jQuery.makeArray( selector, this );
},
另附上makeArray方法与merge方法,merge方法好神奇啊,
复制代码 代码如下: