IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    attribute 与 property · 看不见我的美 · 是你瞎了眼

    馬腊咯稽发表于 2019-05-25 00:00:00
    love 0
    attribute 与 property

    区别

    1. attribute 指的是 HTML 的属性,property 指的是 DOM 对象(JS 对象)的属性;
    2. 非自定义的 attribute 特性与 property 有映射关系,比如:id,class 等;
    3. attribute 的值只能是字符串,property 的值可以是任意类型;
    4. 两者是可以相互影响的。
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    
    <label for="man">
     <input
     id="man"
     class="div-ele"
     type="radio"
     name="SEX"
     checked="false"
     data-pf="boy"
     />
     <span>Man</span>
    </label>
    <label for="woman">
     <input id="woman" class="div-ele" type="radio" name="SEX" data-pf="girl" />
     <span>Woman</span>
    </label>
    <script>
     console.log(document.querySelectorAll('input'));
    </script>
    

    总结

    可以看到 attribute 只是 DOM 对象的 property 之一,保存着对应元素在 HTML 代码中的所有属性;其中 attribute 的值全部为字符串,而 property 的值可以为字符串、对象、数组、布尔值、null、undefined 等。

    为了操作 DOM 的简便,除了自定义属性,大部分 attribute 在 property 里都有对应的映射;修改其一等价于修改另一个。其中 for 和 class 为 JS 的保留字,所以 attribute 的 for/class 属性映射到了 property 的 htmlFor/className。

    因为 attribute 的属性值只能为字符串,所以当我们在 HTML 中加上‘checked=“false”’时,false 会被当作是长度为 5 的字符串,被隐式转换为 true,所以默认“man”被选中。因此 在设置“以非字符串为属性值”的属性时,应该在 JS 中设置 property。



沪ICP备19023445号-2号
友情链接