前幾天,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"