前几天,angular 项目里实现属性绑定的时候发现了个小问题,这是个人代码:javascript
<input type="checkbox" [attr.checked]="item.data.isEnabled">
html
但代码并无生效。而后查了 angular 文档里的属性绑定,文档是这样说的:java
HTML attribute vs. DOM property The distinction between an HTML attribute and a DOM property is crucial to understanding how Angular binding works.- Attributes are defined by HTML.数组
- Properties are defined by the DOM (Document Object Model).
- A few HTML attributes have 1:1 mapping to properties. id is one example.
- Some HTML attributes don't have corresponding properties. colspan is one example.
- Some DOM properties don't have corresponding attributes. textContent is one example.
Many HTML attributes appear to map to properties ... but not in the way you might think!That last category is confusing until you grasp this general rule: Attributes initialize DOM properties and then they are done. Property values can change; attribute values can't.The HTML attribute and the DOM property are not the same thing, even when they have the same name.app
上面那段话翻译过来以下:ide
property 的值是能够改变的,attribute 是不能够改变的,HTML attribute 和 DOM property 虽然名字类似,可是不同的东西。如今,我以项目中的那句代码为例进行简单分析。this
index.html:spa
<body> <div class="switch"> <input type="checkbox" id="switchButton" name="switchButton" value="11" sth="whatevert"> <label class="slider round" for="switchButton"></label> </div> </body> <script> var attr = document.getElementById('switchButton'); console.log(attr); console.log(attr.attributes) </script>
其中执行 console.log(attr);打印出来的就是 property的内容:翻译
从图中能够看到 DOM propertites 是对象数组,其中 checked:false 属于 DOM properties 中的其中一项,而 attributes 是 properties 的一个名为 NamedNodeMap 的子集,它的内容为:code
能够看到这个子集不是一个严格意义上的子集,由于 attributes 中的 sth="whatevert" 属性,在 properties 上并无。执行下面代码:
console.log(attr.sth);//underfined console.log(attr.attributes.sth);//sth="whatevert"