gpt4 book ai didi

javascript cloneNode 和属性

转载 作者:行者123 更新时间:2023-12-02 20:31:11 24 4
gpt4 key购买 nike

是否有一种快速方法来“ super ”深度克隆节点(包括其属性)? (我猜还有方法)

我有这样的东西:

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

var theClone = theSource.cloneNode(true);

alert(theClone.dictator);

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

//编辑

@法布里齐奥

您的 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循环

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

关于javascript cloneNode 和属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4094811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com