jQuery对象初始化传参数形式
今天学习了jQuery对象初始化的传参方式,和大家分享一下:
jQuery对象初始化的传参方式包括:
1.$(DOMElement)
2.$('<h1>...</h1>'),$('#id'),$('.class')传入字符串,这是最常见的形式,这种传参数经常也传入第二个参数context指定上下文,其中context参数可以为$(...),DOMElement
3.$(function(){});<===>$(document).ready(function(){});
4.$({selector:'.class',context:context})<===>$('.class',context)
jQuery.fn=jQuery.prototype={
constructor:jQuery,
init:function(selector,context,rootjQuery){
varmatch,elem,ret,doc;
//处理$(""),$(null),$(undefined),$(false)这几种参数,直接返回this
if(!selector){
returnthis;
}
//当传参selector为DOM结点时,将context置为selector
if(selector.nodeType){
this.context=this[0]=selector;
this.length=1;
returnthis;
}
//HandleHTMLstrings
//当传入的selector参数为字符串时,
if(typeofselector==="string"){
if(selector.charAt(0)==="<"&&selector.charAt(selector.length-1)===">"&&selector.length>=3){
//Assumethatstringsthatstartandendwith<>areHTMLandskiptheregexcheck
match=[null,selector,null];
}else{
match=rquickExpr.exec(selector);
}
//Matchhtmlormakesurenocontextisspecifiedfor#id
if(match&&(match[1]||!context)){
//HANDLE:$(html)->$(array)
if(match[1]){
context=contextinstanceofjQuery?context[0]:context;
doc=(context&&context.nodeType?context.ownerDocument||context:document);
//scriptsistrueforback-compat
selector=jQuery.parseHTML(match[1],doc,true);
if(rsingleTag.test(match[1])&&jQuery.isPlainObject(context)){
this.attr.call(selector,context,true);
}
returnjQuery.merge(this,selector);
//HANDLE:$(#id)
}else{
elem=document.getElementById(match[2]);
//CheckparentNodetocatchwhenBlackberry4.6returns
//nodesthatarenolongerinthedocument#6963
if(elem&&elem.parentNode){
//HandlethecasewhereIEandOperareturnitems
//bynameinsteadofID
if(elem.id!==match[2]){
returnrootjQuery.find(selector);
}
//Otherwise,weinjecttheelementdirectlyintothejQueryobject
this.length=1;
this[0]=elem;
}
this.context=document;
this.selector=selector;
returnthis;
}
//HANDLE:$(expr,$(...))
}elseif(!context||context.jquery){
return(context||rootjQuery).find(selector);
//HANDLE:$(expr,context)
//(whichisjustequivalentto:$(context).find(expr)
}else{
returnthis.constructor(context).find(selector);
}//www.everclub.cn
//HANDLE:$(function)
//Shortcutfordocumentready
//当selector为function时相当于$(document).ready(selector);
}elseif(jQuery.isFunction(selector)){
returnrootjQuery.ready(selector);
}
//当selector参数为{selector:'#id',context:document}之类时,重置属性selector和context
if(selector.selector!==undefined){
this.selector=selector.selector;
this.context=selector.context;
}
returnjQuery.makeArray(selector,this);
}
};