HcySunYang / vue-design

📖 master分支:《渲染器》
http://hcysun.me/vue-design/zh/
6k stars 916 forks source link

Attributes 和 DOM Properties的解释错误 #247

Closed ido-eg closed 5 years ago

ido-eg commented 5 years ago

渲染器之挂载 --> Attributes 和 DOM Properties

给出的例子:

// checkbox 元素
const checkboxEl = document.querySelector("input");
// 使用 setAttribute 设置 checked 属性为 false
checkboxEl.setAttribute("checked", false);

console.log(checkboxEl.checked); // true

解释为:

可以看到虽然我们使用 setAttribute 函数将复选框的 checked 属性设置为 false,但是当我们访问 checkboxEl.checked 时得到的依然是 true,这是因为在 setAttribute 函数为元素设置属性时,无论你传递的值是什么类型,它都会将该值转为字符串再设置到元素上,所以如下两句代码是等价的:

checkboxEl.setAttribute("checked", false);
// 等价于
checkboxEl.setAttribute("checked", "false");

checkboxEl.checked没变的原因应该是:

一些特殊的attribute,比如checked/disabled 等,只要出现了,对应的property就会被初始化为 true,无论设置的值是什么,只有调用removeAttribute删除这个attribute,对应的property 才会变成false

还有一个想说的是关于自定义的attributesetAttribute方法的解释,有些问题:

由于 custom 是非标准属性,所以当你尝试通过 document.body.custom 访问其值时会得到 undefined,这也是为什么会有 setAttribute 方法存在的原因,因为该方法允许我们为 DOM 元素设置自定义属性

实际上setAttribute方法的行为,和浏览器解析 html 中自定义attribute是一致的,都是通过attribute去初始化property,只有html定义的标准attribute才会初始化对应的property,非html定义的,是不会解析到property上的。innerHTMLtextContent属于 DOM propertyhtml定义中没有对应的 attribute,所以和自定义的attribute是一样的道理。