我們每天都在寫 $(),但很少想過它到底能接受多少種形式的參數。把這件事弄清楚,讀 jQuery 原始碼時會順暢很多。
$(DOMElement):把原生 DOM 節點包裝成 jQuery 物件。$('<h1>...</h1>')、$('#id')、$('.class'):傳入字串,這是最常見的用法。這種形式通常還會帶第二個參數 context 指定搜尋上下文,而 context 本身可以是 $(...) 或原生 DOMElement。$(function(){}),等同於 $(document).ready(function(){})。$({selector:'.class', context: context}),等同於 $('.class', context)。
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// 處理 $(""), $(null), $(undefined), $(false),直接回傳 this
if ( !selector ) {
return this;
}
// selector 是 DOM 節點時,把它同時當成 context
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// selector 是字串時的種種判斷
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" &&
selector.charAt( selector.length - 1 ) === ">" &&
selector.length >= 3 ) {
// 前後都是角括號,視為 HTML 片段,跳過正則檢查
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context && context.nodeType ? context.ownerDocument || context : document );
selector = jQuery.parseHTML( match[1], doc, true );
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
this.attr.call( selector, context, true );
}
return jQuery.merge( this, selector );
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
if ( elem && elem.parentNode ) {
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function) —— ready 的快捷寫法
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
// selector 是 {selector:'#id', context:document} 這類物件時,重置兩個屬性
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
}
};
!selector 時直接回傳空的 jQuery 物件,所以 $("#不存在的id") 不會報錯,這也是 jQuery 「容錯」設計的起點。length 設為 1。<> 就走 parseHTML 建立節點;否則交給 rquickExpr 判斷是 #id 還是其他表達式。$(context).find(selector),這在大型頁面裡是實打實的效能優化。$(function(){}) 和 $(document).ready() 完全等價。讀懂這段 init,你對「jQuery 物件為什麼像陣列、為什麼方法都能串接」也會跟著有概念。