我正在开发一个编辑器,并希望使用 JavaScript 克隆具有自定义属性的 HTML 节点。 我只找到a way using setAttribute()但它将我的自定义属性转换为字符串:
// Using custom attributes
var html = document.createElement("div");
var obj = {test: 123,html: html};
html.obj = obj;
var cloned = html.cloneNode(true);
console.log(cloned.obj); // returns null
// Using setAttribute
var html = document.createElement("div");
var obj = {test: 123, html: html};
html.setAttribute("obj") = obj;
var cloned = html.cloneNode(true);
console.log(cloned.getAttribute("obj")); // returns "[object Object]"
如何使用对象克隆 html 元素?
最佳答案
HTML 中的属性是字符串值,而不是 JavaScript 对象和 JavaScript 属性。 cloneNode
操作仅克隆 HTML 内在函数,而不克隆您在顶部添加的任何内容,它与深层对象复制不同。
您需要手动执行此操作:
function cloneCustomNode(node) {
var clone node.cloneNode(); // the deep=true parameter is not fully supported, so I'm not using it
clone.obj = node.obj; // this will copy the reference to the object, it will not perform a deep-copy clone of the 'obj' object
return clone;
}
这可以概括为将任何自定义 JavaScript 属性从一个对象复制到另一个对象,不包括默认值 (defaultNode
) 中已定义的属性。
var defaultNode = document.createElement("div");
function cloneNodeWithAdditionalProperties(node) {
var clone node.cloneNode();
for(var propertyName in node) {
if( !( propertyName in genericNode ) ) {
clone[ propertyName ] = node[ propertyName ];
}
}
return clone;
}
cloneNodeWithAdditionalProperties
将在 O( n )
时间内运行,因为 if( x in y )
操作是使用 进行哈希表查找O( 1 )
复杂度(其中 n
是属性数量)。
关于javascript - 如何克隆具有自定义属性的 HTML 节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41429050/