【js】简单模拟JQuery原理

       
 
       /*
                模拟工厂函数
            */
            function L(selector){
                var eles = document.querySelectorAll(selector);
                var obj =new LQuery();
                eles.forEach(function(item,index){
                    obj[index]=item;
                })
                obj.length=eles.length;
                return obj;
            }
            /*
                模拟Jquery函数对象
            */
            function LQuery(){
               
            }
            LQuery.prototype={
        setHtml:function(val){
                    if(this.length>0){
                        for(var i=0;i<this.length;i++){
                            this[i].innerHTML=val;
                        }
                    }else{
                        throw new DOMException("null pointer exception")
                    }
                    return this;
                }
            }
      //测试
      window.onload=function(){
         L("div").setHtml("<h1>test</h1>")
       } 
 
 
      //html部分
  
      <div></div>
          <div></div>

posted on 2018-01-08 00:42  0X000  阅读(117)  评论(0编辑  收藏  举报

导航