-->

为什么cloneNode排除自定义属性?(Why does cloneNode exclude cu

2019-09-21 00:17发布

这是有关这个问题的JavaScript cloneNode和属性 。

我看到相同的行为。 Node.cloneNode不超过我自己添加(代码从原来的职位)的任何属性复制:

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

    var theClone = theSource.cloneNode(true);
    alert(theClone.dictator); 

theClone不含任何财产“独裁者”。

我一直没能找到为什么是这样的情况下,任何的解释。 在上MDN文档指出cloneNode “所有的属性及属性值的副本”,这是直接取自线DOM规范本身。

因为它使得它几乎不可能做到这一点包含自定义属性DOM树的深层副本,这似乎打破了我。

我失去了一些东西在这里?

Answer 1:

属性是不等于一个属性。

使用的setAttribute()和的getAttribute()来代替。

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

var theClone = theSource.cloneNode(true);
alert(theClone.getAttribute('dictator')); 


Answer 2:

并不是每一个属性对应的属性。 添加自定义属性的元素不添加属性,所以,当你这样做是不包括在DOM规范时会发生什么。

事实上,什么,当你添加一个属性到主机的对象(如DOM节点)是完全不确定的,并且是不保证工作手段发生,所以我强烈反对这样做。 相反,我倒是建议,如果你想延长主机对象的功能(如jQuery和许多其他图书馆一样)使用的包装。



Answer 3:

测试了。 cloneNode 包括在克隆自定义属性,但属性不能直接检索。 尝试:

 var theSource = document.getElementById("someDiv")
 theSource.dictator = "stalin";
 //or better / more cross browser compatible
 theSource.setAttribute('dictator','stalin');

 var theClone = theSource.cloneNode(true);
 alert(theClone.getAttribute('dictator')); //so, use getAttribute 

这可能是一个浏览器的问题,克隆expando properties 。 我跑了测试用例 (见下文),从这个相当老的Bugzilla报告 。 它没有在Chrome和Firefox(均为最新版本)的工作。

//code from testcase @ bugzilla
var a = document.createElement("div");      
a.order = 50;      
alert(a.order);      
b = a.cloneNode(true);      
alert(b.order);    


文章来源: Why does cloneNode exclude custom properties?