appendChild方法会改变node的parentNode
看下面的一个例子
function insertBefore(html,targetElement,callback)
{
var pNode = targetElement.parentNode;
var temp = document.createElement("div");
temp.innerHTML = html;
var frag = document.createDocumentFragment();
(function(){
if(temp.firstChild){
frag.appendChild(temp.firstChild);
//temp.removeChild(temp.firstChild);
setTimeout(arguments.callee,0);
}else{
pNode.insertBefore(frag,targetElement);
if(callback){
callback();
}
}
})()
}
注意注释的部分
有的觉得里面会产生死循环
应该一直都在取temp的firstChild,感觉firstChild一直没有改变
但是其实元素被append到另外一个节点上之后,他的parentNode已经不是temp了
那么等于说temp的firstChild已经没有了,变成下一个节点了
所以不会有死循环问题