javascript – 为什么cloneNode会排除自定义属性?

这与问题javascript cloneNode and properties有关.

我看到了同样的行为. Node.cloneNode不会复制我自己添加的任何属性(来自原始帖子的代码):

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

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

theClone不包含任何属性“独裁者”.

我无法找到任何解释为什么会这样. documentation on MDN声明cloneNode“复制其所有属性及其值”,这条线直接取自DOM specification本身.

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

在这里错过了什么吗?

最佳答案
属性不等于属性.

请改用setAttribute()和getAttribute().

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

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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...