下面是封装初步,$()获取元素和$().调用方法,代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .color-red{ color: red; } </style> </head> <body> <div class="zz">ddd</div> <div class="zz">dd3d</div> <div class="zz">ddd4</div> <p id="z">dd</p> <script> (function (w) { var arr = []; var jQuery = function (selector) { return new jQuery.fn.init(selector); }; jQuery.trim = function (str) { if(typeof str !== 'string') { return str; } if(str.trim()) { return str.trim(); }else { return str.replace(/^\s+|\s+$/g,''); } }; jQuery.fn = jQuery.prototype = { //jQuery外部使用的 $("p").outsideFun(); constructor:jQuery, outsideFun:function () { jQuery.insideFun(); }, addClass:function (str) { if(!str){ console.log("请输入要增加的类名") }else{ str = jQuery.trim(str); for(var i=0;i<this.length;i++){ this[i].classList.add(str) } } } }; var init = jQuery.fn.init = function (selector) { //获取元素begin if( !selector ) { return this; } selector = jQuery.trim(selector); if(typeof selector === 'string'){ var firstStr = selector.slice(0,1); if( firstStr == '#' ){ var tempEle = document.getElementById(selector.slice(1,selector.length)); arr.push.call(this,tempEle); }else if( firstStr == '.' ){ var tempEles = document.getElementsByClassName(selector.slice(1,selector.length)); for(var i=0;i<tempEles.length;i++){ this[i] = tempEles[i]; } this.length = tempEles.length; }else{ var tars = document.getElementsByTagName(selector); for(var j=0;j<tars.length;j++){ this[j] = tars[j]; } this.length = tars.length; } } //获取元素end }; jQuery.extend = jQuery.fn.extend = function () { var tempObj = arguments[0] || {}; for(var key in tempObj){ this[key] = tempObj[key]; } }; jQuery.extend({ //jQuery内部使用的 jQuery.insideFun(); insideFun:function () { console.log("dsy") } }); init.prototype = jQuery.fn; window.$ = window.jQuery = jQuery; return jQuery; })(window); $("p").outsideFun(); $.insideFun(); $("div").addClass("color-red"); </script> </body> </html>本人自己的理解是,jQuery.extend({})这个函数参数里面的方法是给jQuery使用,在jQuery内部要调用这里面的方法时使用jQuery.funName(),外部使用的话直接jQuery.funName(),如果是jQuery.fn.extend({})这种形式调用就是给获取到的对象使用了。在jQuery.fn这个对象里面的方法是给$()获取到的元素对象使用的,如$("div").addClassName()这种的。