2010-11-04 69 views
0

有没有一种快速方法来“超级”深入克隆一个节点,包括它的属性? (和方法,我猜)javascript cloneNode和属性

我有这样的事情:

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); } 
} 

回答

2

可能保存大量属性的最佳方法是创建一个属性对象,您可以在其中存储所有属性,例如

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; 
    } 
}