javascript cloneNode和属性 [英] javascript cloneNode and properties

查看:87
本文介绍了javascript cloneNode和属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种超级深度克隆节点的快速方法,包括其属性? (和方法,我猜)

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

我有这样的事情:

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

var theClone = theSource.cloneNode(true);

alert(theClone.dictator); 

新的克隆对象没有 dictator 属性。现在,假设我有一千个属性附加到 theSource - 我怎样(非显式)将它们传输/复制到克隆?

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?

//编辑

@Fabrizio

@Fabrizio

您的 hasOwnProperty 答案无法正常工作,所以我调整了它。这是我正在寻找的解决方案:

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


推荐答案

可能是最好的方法保存很多属性就是创建一个属性对象,你可以在其中存储所有属性,例如

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

这篇关于javascript cloneNode和属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆