JS模拟JQ:hasClass、addClass、removeClass方法(初探JQ)
2019-01-22 14:56 小花儿鹿 阅读(565) 评论(0) 编辑 收藏 举报<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JQuery初探</title> </head> <body> <div id="box1" class="box"> <span>1112</span> </div> <div id="box2" class="box"> <span>1113</span> </div> <div id="box3" class="box"> <span>1113</span> </div> <script> var Kodo = function(selector){ return new Kodo.prototype.init(selector); } Kodo.prototype = { constructor : Kodo, length : 0, splice : [].splice, selector : '', ele : {}, className : '', idName : '', init : function(selector){ if(selector){ if(selector.substring(0,1) === '#') this.ele = this.createrEleById(selector.substring(1,selector.length)); else if(selector.substring(0,1) === '.') this.ele = this.createEleByClass(selector.substring(1,selector.length)); } //console.log(this.ele); }, createrEleById : function(idName){ this.idName = idName; this.length ++; return document.getElementById(idName); }, createEleByClass : function(className){ var classObj = document.getElementsByClassName(className); this.className = className; this.length = classObj.length; return classObj; }, toTrim : function(str){ //去除字符串两端空格 return str.replace(/(^\s*)|(\s*$)/g, ""); }, hasClass : function(cls){ var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)'); for(var i = 0;i < this.length;i++){ if(this.ele[i].className.match(reg)) return true; } return false; }, addClass : function(cls){ var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)'); for(var i = 0;i < this.length;i++){ if(!this.ele[i].className.match(reg)) //两类名中间需要使用空格进行隔开 this.ele[i].className += ' ' + cls; } return this; }, removeClass : function(cls){ //两种可能,一种可能是删除最原始的className,一种可能是删除新加的className var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)'); for(var i = 0;i < this.length;i ++){ if(this.ele[i].className.match(reg)){ this.ele[i].className = this.ele[i].className.replace(' ' + cls,''); if(this.className.match(reg)){ this.length --;i --; } } } return this; } } Kodo.prototype.init.prototype = Kodo.prototype; Kodo.prototype.ajax = function(){ console.log('这里可以写ajax'); } window.$ = Kodo; console.log($('.box').hasClass('box'),$('.box').hasClass('box1')); $('.box').addClass('box1').removeClass('box'); //目前存在的bug在于无法连续的removeClass,以后有时间再考虑这个问题 </script> </body> </html>