javascript克隆节点和属性
有没有一种快速“超级”深度克隆节点(包括其属性)的方法?(我想还有方法) 我有这样的想法:javascript克隆节点和属性,javascript,properties,clonenode,Javascript,Properties,Clonenode,有没有一种快速“超级”深度克隆节点(包括其属性)的方法?(我想还有方法) 我有这样的想法: var theSource = document.getElementById("someDiv") theSource.dictator = "stalin"; var theClone = theSource.cloneNode(true); alert(theClone.dictator); 新克隆的对象没有独裁者属性。现在,假设我有一千个属性附加到源中,我如何(非显式地)将它们传输/复制到
var theSource = document.getElementById("someDiv")
theSource.dictator = "stalin";
var theClone = theSource.cloneNode(true);
alert(theClone.dictator);
新克隆的对象没有独裁者
属性。现在,假设我有一千个属性附加到源中,我如何(非显式地)将它们传输/复制到克隆中
//编辑
@法布里齐奥
你的hasOwnProperty
答案不正确,所以我调整了它。这就是我一直在寻找的解决方案:
temp = obj.cloneNode(true);
for(p in obj) {
if(obj.hasOwnProperty(p)) { eval("temp."+p+"=obj."+p); }
}
保存大量属性的最佳方法可能是创建一个属性对象,您可以在其中存储所有属性,例如
thesource.myproperties = {}
thesource.myproperties.dictator1 = "stalin";
thesource.myproperties.dictator2 = "ceasescu";
thesource.myproperties.dictator3 = "Berlusconi";
...
那么你只需要复制一个属性
theclone.myproperties = thesource.myproperties
否则,对存储的所有属性执行循环
for (p in thesource) {
if (thesource.hasOwnProperty(p)) {
theclone.p = thesource.p;
}
}