jQuery核心部分原理的模擬代碼
51CTO之前報(bào)道過《jQuery 1.4十大新特性解讀及代碼示例》,為了便于理解,將jQuery的核心使用比較簡單的代碼模擬一下。核心部分實(shí)現(xiàn)了兩種選擇器,使用id和標(biāo)記名,還可以提供CSS的設(shè)置,以及tex的設(shè)置。
51CTO推薦閱讀:jQuery四大天王:核心函數(shù)詳解
- //#表示在 jQuery 1.4.2 中對應(yīng)的行數(shù)
- // 定義變量 undefined 方便使用
- var undefinedundefined = undefined;
- // jQuery 是一個(gè)函數(shù),其實(shí)調(diào)用 jQuery.fn.init 創(chuàng)建對象
- var $ = jQuery = window.$ = window.jQuery// #19
- = function (selector, context) {
- return new jQuery.fn.init(selector, context);
- };
- // 用來檢查是否是一個(gè) id
- idExpr = /^#([\w-]+)$/;
- // 設(shè)置 jQuery 的原型對象, 用于所有 jQuery 對象共享
- jQueryjQuery.fn = jQuery.prototype = { // #74
- length: 0, // #190
- jquery: "1.4.2", // # 187
- // 這是一個(gè)示例,僅僅提供兩種選擇方式:id 和標(biāo)記名
- init: function (selector, context) { // #75
- // Handle HTML strings
- if (typeof selector === "string") {
- // Are we dealing with HTML string or an ID?
- match = idExpr.exec(selector);
- // Verify a match, and that no context was specified for #id
- if (match && match[1]) {
- var elem = document.getElementById(match[1]);
- if (elem) {
- this.length = 1;
- this[0] = elem;
- }
- }
- else {
- // 直接使用標(biāo)記名
- var nodes = document.getElementsByTagName(selector);
- for (var l = nodes.length, j = 0; j < l; j++) {
- this[j] = nodes[j];
- }
- this.length = nodes.length;
- }
- this.context = document;
- this.selector = selector;
- return this;
- }
- },
- // 代表的 DOM 對象的個(gè)數(shù)
- size: function () { // #193
- return this.length;
- },
- // 用來設(shè)置 css 樣式
- css: function (name, value) { // #4564
- this.each(
- function (name, value) {
- this.style[name] = value;
- },
- arguments // 實(shí)際的參數(shù)以數(shù)組的形式傳遞
- );
- return this;
- },
- // 用來設(shè)置文本內(nèi)容
- text: function (val) {// #3995
- if (val) {
- this.each(function () {
- this.innerHTML = val;
- },
- arguments // 實(shí)際的參數(shù)以數(shù)組的形式傳遞
- )
- }
- return this;
- },
- // 用來對所有的 DOM 對象進(jìn)行操作
- // callback 自定義的回調(diào)函數(shù)
- // args 自定義的參數(shù)
- each: function (callback, args) { // #244
- return jQuery.each(this, callback, args);
- }
- }
- // init 函數(shù)的原型也就是 jQuery 的原型
- jQueryjQuery.fn.init.prototype = jQuery.prototype; // #303
- // 用來遍歷 jQuery 對象中包含的元素
- jQuery.each = function (object, callback, args) { // #550
- var i = 0, length = object.length;
- // 沒有提供參數(shù)
- if (args === undefined) {
- for (var value = object[0];
- i < length && callback.call(value, i, value) !== false;
- value = object[++i])
- { }
- }
- else {
- for (; i < length; ) {
- if (callback.apply(object[i++], args) === false) {
- break;
- }
- }
- }
- }
在jQuery中, jQuery對象實(shí)際上是一個(gè)仿數(shù)組的對象,代表通過選擇器得到的所有DOM對象的集合,它像數(shù)組一樣有l(wèi)ength屬性,表示代表的DOM對象的個(gè)數(shù),還可以通過下標(biāo)進(jìn)行遍歷。
95行的jQuery.each是jQuery中用來遍歷這個(gè)仿數(shù)組,對其中的每個(gè)元素進(jìn)行遍歷處理的基本方法,callback表示處理這個(gè)DOM對象的函數(shù)。通常情況下,我們并不使用這個(gè)方法,而是使用 jQuery對象的each方法進(jìn)行遍歷。jQuery對象的css和text方法在內(nèi)部實(shí)際上使用jQuery對象的each方法對所選擇的元素進(jìn)行處理。