attributes和property同步问题

attribute property是什么?
  • 什么是attribute?
    html标签的预定义和自定义属性我们统称为attribute,既图中attributes(想出现在列表里必须在html上显示声明过)
  • 什么是property?
    js原生 DOM对象的直接属性(固有属性),我们统称为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的属性值为布尔类型的 我们统称为布尔值属性
  • property的属性值为非布尔类型的 我们统称为非布尔值属性
attribute和property的同步关系
  • 非布尔值属性: 实时同步
  • 布尔值属性:
    - property永远都不会同步attribute
    - 在没有动过property的情况下(html中没有书写相关属性) attribute首次会同步property
    - 在动过property的情况下 attribute不会同步property
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容