@2890594972
2018-01-18T08:13:04.000000Z
字数 1447
阅读 760
封装jquery

封装代码
// 名字:jQuery 提供两个方法:静态,实例化方法// 使用闭包,封装jquery// $('#demo').css('backgroundColor','red');// jQuery('#demo').css('backgroundColor','red');var jQuery = (function(win){var win = win;function jQuery(selector){this.dom = [];if (typeof selector === 'object'){this.dom.push(selector);}else{// 改造var first = selector.charAt(0);switch (first) {case '#':this.dom[0] = document.getElementById(selector.slice(1));break;case '.':this.dom = document.getElementsByClassName(selector.slice(1));break;}}}// 原型方法jQuery.prototype.css = function(key, value){// this.dom.style[key] = value;var arr = this.dom;for (var i = 0; i < arr.length ; i++){arr[i].style[key] = value;}return this;}// 绑定事件jQuery.prototype.click = function(callback){var arr = this.dom;for(var i = 0; i< arr.length; i++){arr[i].onclick = (function(obj){ // 闭包return function(){// console.log(obj);callback.call(obj);}})(arr[i]);}}// 静态方法jQuery.each = function(){console.log(12345);}return jQuery;})(window);function $(selector){return new jQuery(selector);}$('#demo').css('background', 'red').css('fontSize', '100px').css('borderRadius', '20px').css('color','#fff');$('.class-haha').css('background', 'red').css('fontSize', '100px').css('borderRadius', '20px').css('color', '#fff');// $('#demo').css('fontSize','100px');// // jQuery('#demo').css('borderRadius','20px');// 使用方式$('.class-haha').click(function(){// console.log(111111111111111111,this);// this.style.backgroundColor = 'blue';// console.log(typeof this);$(this).css('backgroundColor','blue');})// jQuery.each();
