init 構造器
由于這個函數直接和 jQuery() 的參數有關,先來說下能接受什么樣的參數。
源碼中接受 3 個參數:
init: function (selector, context, root) { ...}jQuery() ,空參數,這個會直接返回一個空的 jQuery 對象,return this。 jQuery( selector [, context ] ) ,這是一個標準且常用法,selector 表示一個 css 選擇器,這個選擇器通常是一個字符串,#id 或者 .class 等,context 表示選擇范圍,即限定作用,可為 DOM,jQuery 對象。 jQuery( element|elements ) ,用于將一個 DOM 對象或 DOM 數組封裝成 jQuery 對象。 jQuery( jQuery object|object ) ,會把普通的對象或 jQuery 對象包裝在 jQuery 對象中。 jQuery( html [, ownerDocument ] ) ,這個方法用于將 html 字符串先轉成 DOM 對象后在生成 jQuery 對象。 jQuery( html, attributes ) ,和上一個方法一樣,不過會將 attributes 中的方法和屬性綁定到生成的 html DOM 中,比如 class 等。 jQuery( callback ) ,此方法接受一個回掉函數,相當于 window.onload 方法,只是相對于。介紹完入口,就開始來看源碼。
init: function (selector, context, root) { var match, elem; // 處理: $(""), $(null), $(undefined), $(false) if (!selector) { return this; } // rootjQuery = jQuery( document ); root = root || rootjQuery; // 處理 HTML 字符串情況,包括 $("<div>")、$("#id")、$(".class") if (typeof selector === "string") { //此部分拆分,留在后面講 // HANDLE: $(DOMElement) } else if (selector.nodeType) { this[0] = selector; this.length = 1; return this; // HANDLE: $(function) } else if (jQuery.isFunction(selector)) { return root.ready !== undefined ? root.ready(selector) : // Execute immediately if ready is not present selector(jQuery); } return jQuery.makeArray(selector, this);}上面有幾點需要注意,root = root || rootjQuery; ,這個參數在前面介紹用法的時候,就沒有提及,這個表示 document,默認的話是 rootjQuery,而 rootjQuery = jQuery( document ) 。
可以看出,對于處理 $(DOMElement) ,直接是把 jQuery 當作一個數組,this[0] = DOMElement 。其實,這要從 jQuery 的基本構造講起,我們完成一個 $('div.span') 之后,然后一個 jQuery 對象(this),其中會得到一組(一個)DOM 對象,jQuery 會把這組 DOM 對象當作數組元素添加過來,并給一個 length。后面就像一些鏈式函數操作的時候,若只能對一個 DOM 操作,比如 width、height,就只對第一個元素操作,若可以對多個 DOM 操作,則會對所有 DOM 進行操作,比如 css()。
jQuery 大題思路如下,這是一個非常簡單點實現:
新聞熱點
疑難解答
圖片精選