javascript cloneNode and properties

痞子三分冷 提交于 2019-12-30 15:02:12

问题


Is there a quick way to "super" deep clone a node, including its properties? (and methods, I guess)

I've got something like this:

var theSource = document.getElementById("someDiv")
theSource.dictator = "stalin";

var theClone = theSource.cloneNode(true);

alert(theClone.dictator); 

The new cloned object has no dictator property. Now, say I've got a thousand properties attached to theSource - how can I (non-explicitly) transfer/copy them to the clone?

// EDIT

@Fabrizio

Your hasOwnProperty answer doesn't work properly, so I adjusted it. This is the solution I was looking for:

temp = obj.cloneNode(true);

for(p in obj) {
  if(obj.hasOwnProperty(p)) { eval("temp."+p+"=obj."+p); }
}

回答1:


probably the best way to save a lot of properties is to create a property object in which you can store all properties e.g.

thesource.myproperties = {}
thesource.myproperties.dictator1 = "stalin"; 
thesource.myproperties.dictator2 = "ceasescu"; 
thesource.myproperties.dictator3 = "Berlusconi";
...

then you have to copy just one property

theclone.myproperties = thesource.myproperties

otherwise do a for cycle for all properties you have stored

for (p in thesource) {
  if (thesource.hasOwnProperty(p)) {
    theclone.p = thesource.p;
  }
}


来源:https://stackoverflow.com/questions/4094811/javascript-clonenode-and-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!