有没有一种快速的“超级”深度克隆节点,包括它的属性?(我猜,还有方法)
我得到了类似这样的东西:
var theSource = document.getElementById("someDiv")
theSource.dictator = "stalin";
var theClone = theSource.cloneNode(true);
alert(theClone.dictator); 新克隆的对象没有dictator属性。现在,假设我已经将一千个属性附加到theSource --我如何(非显式地)将它们传输/复制到克隆?
//编辑
@Fabrizio
您的hasOwnProperty答案不能正常工作,因此我对其进行了调整。这就是我正在寻找的解决方案:
temp = obj.cloneNode(true);
for(p in obj) {
if(obj.hasOwnProperty(p)) { eval("temp."+p+"=obj."+p); }
}发布于 2010-11-04 16:48:20
保存大量属性的最好方法可能是创建一个属性对象,您可以在其中存储所有属性,例如
thesource.myproperties = {}
thesource.myproperties.dictator1 = "stalin";
thesource.myproperties.dictator2 = "ceasescu";
thesource.myproperties.dictator3 = "Berlusconi";
...然后,您只需复制一个属性
theclone.myproperties = thesource.myproperties否则,对已存储的所有属性执行for循环
for (p in thesource) {
if (thesource.hasOwnProperty(p)) {
theclone.p = thesource.p;
}
}https://stackoverflow.com/questions/4094811
复制相似问题