(function () { //创建一个jquery构造函数 function jquery(selector) { return new jquery.prototype.init(selector); } //为jquery的原型添加init属性,所有实例可以使用该属性 jquery.prototype.init = function (selector) { this.length = 0; //为this添加length属性,并且赋值为0 //选出 dom 并且包装成jquery对象返回 //判断selector是null 和 undefined 和 dom对象 和 id 和 class的情况 if(this == null){//判断selector是null或undefined return this; }if (typeof selector === 'string' && selector.indexof('.') != -1) { //selector是class的情况 var dom = document.getelementsbyclassname(selector.slice(1)); } else if (typeof selector === 'string' && selector.indexof("#") != -1) { //selector是id的情况 var dom = document.getelementbyid(selector.slice(1)); } if (selector instanceof element || dom.length === undefined) { //(selector是dom对象) || (selector是id,返回的是一个对象,对象没有length属性) this[0] = dom || selector;//(selector是id) || (selector是dom对象) this.length++; } else { //selector是class,返回的是一个类数组 for (var i = 0; i < dom.length; i++) { this[i] = dom[i]; this.length++; } } }; //为jquery的原型添加css属性,所有实例可以使用该属性 jquery.prototype.css = function (config) { for (var i = 0; i < this.length; i++) { for (var prop in config) { this[i].style[prop] = config[prop]; } } return this; //链式调用的精髓 }; //为jquery的原型添加get属性,所有实例可以使用该属性 jquery.prototype.get = function (num) { //num == null 返回数组 //num >= 0 返回this[num] //num < 0 返回this[length + num] return (num != null) ? ((num >= 0) ? (this[num]) : (this[num + this.length])) : ([].slice(this, 0)); }; //为jquery的原型添加get属性,所有实例可以使用该属性 jquery.prototype.eq = function (num) { return jquery(this.get(num));//调用jquery.prototype.get()函数获取到dom对象,在封装为jquery对象 }; //上面的jquery构造函数是new 一个jquery.prototype.init对象, //jquery.prototype.init对象上没有jquery.prototype上的css()方法 //所以添加下面一句,让jquery.prototype.init对象可以调用jquery.prototype上的css()方法 jquery.prototype.init.prototype = jquery.prototype; //让外部可以通过$()或者jquery()调用 window.$ = window.jquery = jquery; }());
调用get()和eq()方法:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>document</title> </head> <body> <div id="wrapper">1</div> <div class="demo">2</div> <div class="demo">3</div> <script src="./myjquery.js"></script> <script> console.log($(".demo").get(0), $(".demo").eq(0)); </script> </body> </html>
效果展示:
如对本文有疑问, 点击进行留言回复!!
VScode中的react自动补全标签代码及黄色or红色警告
关于React处理input的方法和多个input共用一个方法(不用jQuery)
网友评论