attribute property是什么?
- 什么是attribute?
html標簽的預定義和自定義屬性我們統(tǒng)稱為attribute,既圖中attributes(想出現(xiàn)在列表里必須在html上顯示聲明過) - 什么是property?
js原生 DOM對象的直接屬性(固有屬性),我們統(tǒng)稱為property 既圖中checked
image.png
為什么要理解這個?
以checkbox 為例
由于用戶操作的是 property,瀏覽器最終認的也是property,
使用attribute相關的接口對布爾值屬性checked的操作 可能不會有 選中/取消 效果
<body>
<input type="checkbox" >
<button>選中</button>
<button>取消</button>
<script>
debugger;
var input = document.querySelector('input[type=checkbox]');
var button1 = document.querySelectorAll('button')[0];
var button2 = document.querySelectorAll('button')[1];
button1.onclick = ()=>{
input.setAttribute('checked',true); // ×
//$(input).attr('checked',true) // ×
// input.checked=true; // √
//$(input).prop('checked',true) // √
}
button2.onclick = ()=>{
input.setAttribute('checked',false);// ×
//$(input).attr('checked',false) // ×
// input.checked=false; // √
//$(input).prop('checked',false) // √
}
</script>
</body>
什么是布爾值屬性?
property的屬性值為布爾類型的 我們統(tǒng)稱為布爾值屬性property的屬性值為非布爾類型的 我們統(tǒng)稱為非布爾值屬性
attribute和property的同步關系
-
非布爾值屬性:實時同步 -
布爾值屬性:
-property永遠都不會同步attribute
-在沒有動過property的情況下(html中沒有書寫相關屬性) attribute首次會同步property
-在動過property的情況下 attribute不會同步property
