核心部分實現了兩種選擇器,使用 id 和標記名,還可以提供 css 的設置,以及 text 的設置。
1 // # 表示在 jQuery 1.4.2 中對應的行數
2
3 // 定義變量 undefined 方便使用
4 var undefined = undefined;
5
6 // jQuery 是一個函數,其實調用 jQuery.fn.init 創建對象
7 var $ = jQuery = window.$ = window.jQuery // #19
8 = function (selector, context) {
9 return new jQuery.fn.init(selector, context);
10 };
11
12 // 用來檢查是否是一個 id
13 idExpr = /^#([w-]+)$/;
14
15 // 設置 jQuery 的原型對象, 用于所有 jQuery 對象共享
16 jQuery.fn = jQuery.prototype = { // #74
17
18 length: 0, // #190
19
20 jquery: "1.4.2", // # 187
21
22 // 這是一個示例,僅僅提供兩種選擇方式:id 和標記名
23 init: function (selector, context) { // #75
24
25 // Handle HTML strings
26 if (typeof selector === "string") {
27 // Are we dealing with HTML string or an ID?
28 match = idExpr.exec(selector);
29
30 // Verify a match, and that no context was specified for #id
31 if (match && match[1]) {
32 var elem = document.getElementById(match[1]);
33 if (elem) {
34 this.length = 1;
35 this[0] = elem;
36 }
37 }
38 else {
39 // 直接使用標記名
40 var nodes = document.getElementsByTagName(selector);
41 for (var l = nodes.length, j = 0; j < l; j++) {
42 this[j] = nodes[j];
43 }
44 this.length = nodes.length;
45 }
46
47 this.context = document;
48 this.selector = selector;
49
50 return this;
51 }
52 },
53
54 // 代表的 DOM 對象的個數
55 size: function () { // #193
56 return this.length;
57 },
58
59 // 用來設置 css 樣式
60 css: function (name, value) { // #4564
61 this.each(
62 function (name, value) {
63 this.style[name] = value;
64 },
65 arguments // 實際的參數以數組的形式傳遞
66 );
67 return this;
68 },
69
70 // 用來設置文本內容
71 text: function (val) { // #3995
72 if (val) {
73 this.each(function () {
74 this.innerHTML = val;
75 },
76 arguments // 實際的參數以數組的形式傳遞
77 )
78 }
79 return this;
80 },
81
82 // 用來對所有的 DOM 對象進行操作
83 // callback 自定義的回調函數
84 // args 自定義的參數
85 each: function (callback, args) { // #244
86 return jQuery.each(this, callback, args);
87 }
88
89 }
90
91 // init 函數的原型也就是 jQuery 的原型
92 jQuery.fn.init.prototype = jQuery.prototype; // #303
93
94 // 用來遍歷 jQuery 對象中包含的元素
95 jQuery.each = function (object, callback, args) { // #550
96
97 var i = 0, length = object.length;
98
99 // 沒有提供參數
100 if (args === undefined) {
101
102 for (var value = object[0];
103 i < length && callback.call(value, i, value) !== false;
104 value = object[++i])
105 { }
106 }
107
108 else {
109 for (; i < length; ) {
110 if (callback.apply(object[i++], args) === false) {
111 break;
112 }
113 }
114 }
115 }
116
在 jQuery 中, jQuery 對象實際上是一個仿數組的對象,代表通過選擇器得到的所有 DOM 對象的集合,它像數組一樣有 length 屬性,表示代表的 DOM 對象的個數,還可以通過下標進行遍歷。
95 行的 jQuery.each 是 jQuery 中用來遍歷這個仿數組,對其中的每個元素進行遍歷處理的基本方法,callback 表示處理這個 DOM 對象的函數。通常情況下,我們并不使用這個方法,而是使用 jQuery 對象的 each 方法進行遍歷。jQuery 對象的 css 和 text 方法在內部實際上使用 jQuery 對象的 each 方法對所選擇的元素進行處理。
這些函數及對象的關系見:jQuery 原型關系圖
下面的腳本使用這個腳本庫。
1 // 原型操作
2 $("h1").text("Hello, world.").css("color", "green");
原文:http://www.cnblogs.com/haogj/archive/2010/08/01/1789712.html