调用库的时候, 我们需要能够在前台调用的时候可以同时设置多个操作, 比如设置CSS, 设置innerHTML, 设置click事件...
这里提到的库只是自己编写的为了方便的“个人代码微库”的部分,非主流框架库
1.连缀介绍:
所谓的连缀其实就是同时给一个或多个节点进行两个或两个以上的操作:
$().getId('box').css('backgroundColor','black').css('color','white').html('你好').click(function(){alert('a')});
好处在于我们可以很方便的进行节点操作的设置
2.简单库对象写法:
var Base = function () {
this.elements = [];
//获取id
this.getId=function(id){
this.elements.push(document.getElementById(id));
return this
}
//获取元素
this.getTagName = function(tagName){
var tags = document.getElementsByTagName(tagName);
for(var i=0;i<tags.length;i++){
this.elements.push(tags[i]);
}
return this;
}
}
Base.prototype.css = function(attr,value){
for(var i =0 ;i<this.elements.length;i++){
this.elements[i].style[attr] = value;
}
return this;
}
Base.prototype.html = function(value){
for(var i=0;i<this.elements.length;i++){
this.elements[i].innerHTML = value;
}
return this;
}
Base.prototype.click = function(fn){
for(var i=0;i<this.elements.length;i++){
this.elements[i].onclick = fn;
}
return this;
}
为了避免每次去New对象,可以直接在库中写上:
var $ = function(){
return new Base();
}
这样就可以很方便的实现连缀操作了,如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>连缀Demo</title>
<script type="text/javascript" src="base.js"></script>
<script type="text/javascript" src="demo.js"></script>
</head>
<body>
<div id="box" >2</div>
<p>P1</p>
<p>P2</p>
</body>
</html>
加上节点操作:
window.onload = function () {
$().getId('box').css('backgroundColor','black').css('color','white').html('你好').click(function(){alert('a')});
$().getTagName('p').html('改变你').click(function(){alert('changed')});
}