attribute property是什么?
- 什么是attribute?
html標(biāo)簽的預(yù)定義和自定義屬性我們統(tǒng)稱為attribute,既圖中attributes(想出現(xiàn)在列表里必須在html上顯示聲明過(guò)) - 什么是property?
js原生 DOM對(duì)象的直接屬性(固有屬性),我們統(tǒng)稱為property 既圖中checked
image.png
為什么要理解這個(gè)?
以checkbox 為例
由于用戶操作的是 property,瀏覽器最終認(rèn)的也是property,
使用attribute相關(guān)的接口對(duì)布爾值屬性checked的操作 可能不會(huì)有 選中/取消 效果
<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的同步關(guān)系
-
非布爾值屬性:實(shí)時(shí)同步 -
布爾值屬性:
-property永遠(yuǎn)都不會(huì)同步attribute
-在沒(méi)有動(dòng)過(guò)property的情況下(html中沒(méi)有書(shū)寫(xiě)相關(guān)屬性) attribute首次會(huì)同步property
-在動(dòng)過(guò)property的情況下 attribute不會(huì)同步property
