attributes和property同步問(wèn)題

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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容