核心部分实现了两种选择器,使用 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 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 value = object[++i]) 
{ } 
} 
else { 
for (; i 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);
   
 
   