jQuery.API源码深入剖析以及应用实现 - 核心函数篇
2010-09-14 13:38:00 来源:WEB开发网从这里我们可以得出,实际上$里面的参数(表达式字符串,ID字符串,HTML字符串,DOM对象),主要就是在init方法中各自实现它们自己的逻辑。
现在列出init方法的具体实现:
init:function(selector,context){
//Makesurethataselectionwasprovided
selector=selector||document;
//Handle$(DOMElement)
if(selector.nodeType){
this[0]=selector;
this.length=1;
this.context=selector;
returnthis;
}
//HandleHTMLstrings
if(typeofselector==="string"){
//ArewedealingwithHTMLstringoranID?
varmatch=quickExpr.exec(selector);
//Verifyamatch,andthatnocontextwasspecifiedfor#id
if(match&&(match[1]||!context)){
//HANDLE:$(html)->$(array)
if(match[1])
selector=jQuery.clean([match[1]],context);
//HANDLE:$("#id")
else{
varelem=document.getElementById(match[3]);
//HandlethecasewhereIEandOperareturnitems
//bynameinsteadofID
if(elem&&elem.id!=match[3])
returnjQuery().find(selector);
//Otherwise,weinjecttheelementdirectlyintothejQueryobject
varret=jQuery(elem||[]);
ret.context=document;
ret.selector=selector;
returnret;
}
//HANDLE:$(expr,[context])
//(whichisjustequivalentto:$(content).find(expr)
}else
returnjQuery(context).find(selector);
//HANDLE:$(function)
//Shortcutfordocumentready
}elseif(jQuery.isFunction(selector))
returnjQuery(document).ready(selector);
//Makesurethatoldselectorstateispassedalong
if(selector.selector&&selector.context){
this.selector=selector.selector;
this.context=selector.context;
}
returnthis.setArray(jQuery.makeArray(selector));
}
更多精彩
赞助商链接