封装库—连缀
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>封装库——连缀</title> 6 <script src="base.js"></script> 7 <script src="demo.js"></script> 8 </head> 9 <body> 10 11 <div id="box">box</div> 12 13 <p>段落</p> 14 <p>段落</p> 15 <p>段落</p> 16 </body> 17 </html>
base.js
1 function Base(){ 2 //创建一个数组来保存获取的节点和节点数组 3 this.elements = []; 4 //获取ID节点 5 this.getId = function(id){ 6 this.elements.push(document.getElementById(id)); 7 return this; 8 }; 9 10 //获取元素节点 11 this.getTagName = function(tag){ 12 var tags = document.getElementsByTagName(tag); 13 for (var i=0; i<tags.length; i++){ 14 this.elements.push(tags[i]); 15 } 16 return this; 17 }; 18 19 } 20 21 Base.prototype.css = function(attr,value){ 22 for (var i=0; i<this.elements.length; i++){ 23 this.elements[i].style[attr] = value; 24 } 25 return this; 26 }; 27 28 Base.prototype.innerhtml = function(str){ 29 for (var i=0; i<this.elements.length; i++){ 30 this.elements[i].innerHTML= str; 31 } 32 return this; 33 }; 34 35 Base.prototype.click = function(fn){ 36 for (var i=0; i<this.elements.length; i++){ 37 this.elements[i].onclick = fn; 38 } 39 return this; 40 };
demo.js
1 window.onload = function(){ 2 $().getId('box').css('color','red').css('backgroundColor','blue'); 3 $().getTagName('p').css('color','green').innerhtml('aaa').click(function(){ 4 alert('nnn'); 5 }).css('background',"red"); //后面的样式会覆盖前面的样式,因为使用的一个原型实例对象,这是需要分开实例化,每个专门一个实例。 6 }