js学习笔记--封装库--连缀

来源:互联网 发布:dayz独立版优化那么差 编辑:程序博客网 时间:2024/05/17 00:56

base.js

/*    Base是一个基础库的核心对象    Base.getId('box').css('color','red')要返回的是Base对象*/var $=function(){    return new Base();}function Base(){    //保存ID节点    this.elements=[];    //获取ID节点    this.getId=function(id){        this.elements.push(document.getElementById(id));        return this;    }     //获取元素节点    this.getTagName=function(tag){        var tags=document.getElementsByTagName(tag);        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(str){    for(var i=0;i<this.elements.length;i++){        this.elements[i].innerHTML=str;    }    return this;}Base.prototype.click=function(fn){    for(var i=0;i<this.elements.length;i++){        this.elements[i].onclick=fn;    }    return this;}

demo.js

window.onload=function(){    var base=new Base();    $().getId('box').css('color','red').css('backgroundColor','yellow');    $().getTagName('p').css('color','red');    $().getTagName('p').html('xiaoxi');    $().getTagName('p').click(function(){        alert("hello");    });};


原创粉丝点击