DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> jQuery入門知識 >> JQuery特效代碼 >> jQuery的實現原理的模擬代碼 -1 核心部分
jQuery的實現原理的模擬代碼 -1 核心部分
編輯:JQuery特效代碼     
核心部分實現了兩種選擇器,使用 id 和標記名,還可以提供 css 的設置,以及 text 的設置。
代碼如下:
// # 表示在 jQuery 1.4.2 中對應的行數
// 定義變量 undefined 方便使用
var undefined = undefined;
// jQuery 是一個函數,其實調用 jQuery.fn.init 創建對象
var $ = jQuery = window.$ = window.jQuery // #19
= function (selector, context) {
return new jQuery.fn.init(selector, context);
};
// 用來檢查是否是一個 id
idExpr = /^#([\w-]+)$/;
// 設置 jQuery 的原型對象, 用於所有 jQuery 對象共享
jQuery.fn = jQuery.prototype = { // #74
length: 0, // #190
jquery: "1.4.2", // # 187
// 這是一個示例,僅僅提供兩種選擇方式:id 和標記名
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 {
// 直接使用標記名
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 對象的個數
size: function () { // #193
return this.length;
},
// 用來設置 css 樣式
css: function (name, value) { // #4564
this.each(
function (name, value) {
this.style[name] = value;
},
arguments // 實際的參數以數組的形式傳遞
);
return this;
},
// 用來設置文本內容
text: function (val) { // #3995
if (val) {
this.each(function () {
this.innerHTML = val;
},
arguments // 實際的參數以數組的形式傳遞
)
}
return this;
},
// 用來對所有的 DOM 對象進行操作
// callback 自定義的回調函數
// args 自定義的參數
each: function (callback, args) { // #244
return jQuery.each(this, callback, args);
}
}
// init 函數的原型也就是 jQuery 的原型
jQuery.fn.init.prototype = jQuery.prototype; // #303
// 用來遍歷 jQuery 對象中包含的元素
jQuery.each = function (object, callback, args) { // #550
var i = 0, length = object.length;
// 沒有提供參數
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 對象實際上是一個仿數組的對象,代表通過選擇器得到的所有 DOM 對象的集合,它像數組一樣有 length 屬性,表示代表的 DOM 對象的個數,還可以通過下標進行遍歷。

95 行的 jQuery.each 是 jQuery 中用來遍歷這個仿數組,對其中的每個元素進行遍歷處理的基本方法,callback 表示處理這個 DOM 對象的函數。通常情況下,我們並不使用這個方法,而是使用 jQuery 對象的 each 方法進行遍歷。jQuery 對象的 css 和 text 方法在內部實際上使用 jQuery 對象的 each 方法對所選擇的元素進行處理。

這些函數及對象的關系見:jQuery 原型關系圖


下面的腳本使用這個腳本庫。
代碼如下:
// 原型操作
$("h1").text("Hello, world.").css("color", "green");
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved