functionappendNode($node, data) {var a, li;for (let i =0, max =data.length; i < max; i++) { a =document.createElement("a"); li =document.createElement("li");a.href = data[i].url;a.appendChild(document.createTextNode(data[i].name));li.appendChild(a);$node.appendChild(li); }}// beforelet ul =document.querySelector("#mylist");appendNode(ul, data);// afterlet ul =document.querySelector("#mylist");ul.style.display ="none";appendNode(ul, data);ul.style.display ="block";
使用文档片段创建一个子树,然后再拷贝到文档中
let fragment =document.createDocumentFragment();appendNode(fragment, data);ul.appendChild(fragment);
将原始元素拷贝到一个独立的节点中,操作这个节点,然后覆盖原始元素
let old =document.querySelector("#mylist");let clone =old.cloneNode(true);appendNode(clone, data);old.parentNode.replaceChild(clone, old);