实现append()难点

来源:互联网 发布:微信支付接口开发 php 编辑:程序博客网 时间:2024/06/15 05:29

append封装

这里写图片描述

这里实现不了jQuery

这里写图片描述

的选中多个div添加 ,只实现了一个div添加..


难点

1.$()判断

    eg: $("<div></div>")
if(type === "string"){ //选择器    if(/^<[^><]+>/.test(param)){  //$(<div>)        var Dom = document.createElement("div");        Dom.innerHTML = param;        this.length = Dom.children.length;        for(var i=0;i<this.length;i++){ //可能多个节点            this[i] = Dom.children[i];        };    }else{        var Doms = document.querySelectorAll(param);        this.length = Doms.length;        //遍历获取的js对象 给 实例化对象的下标下        for(var i=0;i<Doms.length;i++){            this[i] = Doms[i];        };    }}

2.总是节点只能appendChild()一次.所以====>cloneNode(true)节点

同时 不是能忘了操作原节点,

append : function(param){    if(typeof param === "string"){        if(/^<[^><]>/.test(param)){            // 元素节点<div>            this.append($(param));  //$("<div></div>")        }else{            // 文本节点""            var Dom = document.createTextNode(param);            this[0].appendChild(Dom);        }    }else if( typeof param === "object"){        // jQ对象        // 判断jq     append($("p"))   选择p 元素.  [0][1][2]        if(param.constructor === init){            // this[0].appendChild(param[i]);            // 遍历 !!如果选择了多个元素.            // 节点添加之后就消失了,所以只有一个被添加.            // console.log(param);  节点复制一份.            for(var i=0;i<this.length;i++){                for(var j=0;j<param.length;j++){                    if(i == this.length-1){  //当是选择器最后一份,直接操作节点                        var temp = param[j];                    }else{                        var temp = param[j].cloneNode(true);                    }                    this[i].appendChild(temp);                };            }        }else{        // js对象     append(节点))            this.append($(param));  //转换为jQ对象.再调用上面的.        }    }    return this;}
0 0
原创粉丝点击