由于 custom 是非标准属性,所以当你尝试通过 document.body.custom 访问其值时会得到 undefined,这也是为什么会有 setAttribute 方法存在的原因,因为该方法允许我们为 DOM 元素设置自定义属性
实际上setAttribute方法的行为,和浏览器解析 html 中自定义attribute是一致的,都是通过attribute去初始化property,只有html定义的标准attribute才会初始化对应的property,非html定义的,是不会解析到property上的。innerHTML 和 textContent属于 DOM property,html定义中没有对应的 attribute,所以和自定义的attribute是一样的道理。
渲染器之挂载 --> Attributes 和 DOM Properties
给出的例子:
解释为:
checkboxEl.checked
没变的原因应该是:一些特殊的
attribute
,比如checked
/disabled
等,只要出现了,对应的property
就会被初始化为true
,无论设置的值是什么,只有调用removeAttribute
删除这个attribute
,对应的property
才会变成false
。还有一个想说的是关于自定义的
attribute
和setAttribute
方法的解释,有些问题:实际上
setAttribute
方法的行为,和浏览器解析 html 中自定义attribute
是一致的,都是通过attribute
去初始化property
,只有html
定义的标准attribute
才会初始化对应的property
,非html
定义的,是不会解析到property
上的。innerHTML
和textContent
属于 DOMproperty
,html
定义中没有对应的attribute
,所以和自定义的attribute
是一样的道理。