attributes和property同步問題

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

相關閱讀更多精彩內容

友情鏈接更多精彩內容