之前报道过《jQuery 1.4十大新特性解读及代码示例》,为了便于理解,将jQuery的核心使用比较简单的代码模拟一下。核心部分实现了两种选择器,使用id和标记名,还可以提供CSS的设置,以及tex的设置。

在九江等地区,都构建了全面的区域性战略布局,加强发展的系统性、市场前瞻性、产品创新能力,以专注、极致的服务理念,为客户提供成都做网站、成都网站制作 网站设计制作定制网站,公司网站建设,企业网站建设,成都品牌网站建设,网络营销推广,成都外贸网站建设,九江网站建设费用合理。
推荐阅读:jQuery四大天王:核心函数详解
- //#表示在 jQuery 1.4.2 中对应的行数
 - // 定义变量 undefined 方便使用
 - var undefinedundefined = 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 对象共享
 - jQueryjQuery.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 的原型
 - jQueryjQuery.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方法对所选择的元素进行处理。
Copyright © 2009-2022 www.wtcwzsj.com 青羊区广皓图文设计工作室(个体工商户) 版权所有 蜀ICP备19037934号