原生jQuery代碼

function myJquery(selector){    if(typeof selector=="string") {        if (selector.charAt(0) == "<" && selector.slice(-1) == ">") {            var ele = selector.slice(1,-1);            this[0] = document.createElement(ele);            this.length = 1;        } else {            var all=document.querySelectorAll(selector);            for (var i = 0; i < all.length; i++) {                this[i] = all[i];            }            this.length = all.length;        }    }else if(typeof selector=="undefined"){        return this;    }else if(typeof selector=="function"){        this.ready(selector);    }else if(selector.nodeType==1){        this[0]=selector;        this.length=1;    }}myJquery.prototype={    each:function(callback){        for (var i=0;i<this.length;i++){            callback(i,this[i]);        }    },    html:function(val){        this.each(function(index,obj){            obj.innerHTML=val        });        return this;    },    css:function(attr,val){        this.each(function(index,obj){            if (typeof attr=="object"){                for (var i in attr){                    if (i=="width"||i=="height"||i=="margin"||i=="fontSize"){                        obj.style[i]=parseInt(attr[i])+"px";                    }                    obj.style[i]=attr[i];                }            }else{                obj.style[attr]=val;            }        })        return this;    },    ready:function(callback){        document.addEventListener("DOMContentLoaded",function(){            callback();        })    },    click:function(callback){        this.each(function(index,obj){            obj.onclick=function(){                callback.call(obj);            }        })        return this;    },    appendTo:function(dom){        if (typeof dom=="string"){            var all=document.querySelectorAll(dom)            var ele=this[0]            for (var i=0;i<all.length;i++){                this[i]=ele.cloneNode(true)                all[i].appendChild(this[i])                this.length=all.length            }        }else{            dom.appendChild(this[0])        }        // document.querySelector(dom).appendChild(this[0]);        return this;    }}function $(selector){     return new myJquery(selector);}
相關文章
相關標籤/搜索