attribute 和 property 的区别

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37890535/article/details/85528704
  • 一、问题由来

在 jquery1.6 版本增加了 prop() 方法,用于操作 property, 而之前都是通过 attr() 方法操作的, 一直不理解这其中的区别.

  • 二 attribute 和 property 区别
  1. attribute 指的是你在 html 页面中给元素标签设置的属性, 例如下面这个 input 标签中, id, name 就是 attribute.
<input id="test" name="name">
  1. property 指的是标签被浏览器解析生成 DOM 对象后, 这个DOM 对象的属性, 类似于 Java 中由类生成的对象的属性.例如下面这个 DOM 对象, 其中 nodeName, nodeType, nodeValue 是这个 DOM 对象的属性(注意: 这个 DOM 对象经过省略, 实际上它还拥有更多的属性)
input#test
attributes: NamedNodeMap {0: id, 1: name, id: id, name: name, length: 2}
nodeName: "INPUT"
nodeType: 1
nodeValue: null
id: "test"
name: "name"
  1. attribute 和 property 之间的关系
    标签设置的 attribute 属性会存在于生成的 DOM 对象的 attributes 属性中. 例如上面的 input 标签存在两个 attribute, 与此对应的 DOM 对象中 的attributes 属性中就包含了这两个 attribute.

对于标签中每个的 attribute 都存在一个 DOM 对象的 property 与其相对应, 对应的名字不一定相同, 反过来却不成立.并且标签中 attribute 属性值的更改会造成 DOM 对象中 property 属性的更改, 反过来也成立.例如上面 input 标签有 id, name 两个 attribute, 在 DOM 对象中则有 id, name 两个 property.然而对于 DOM 对象的 nodeName property, 在 input 标签中却没有与之对应的 attribute.

标签中还存在一类比较特殊的 attribute, W3C 将其定义为 boolean attribute, 具体定义参考 boolean attribute. 其中的典型代表为标签的 checked, selected, value.它们对应的是 DOM 对象的 defaultChecked, defaultSelected, defaultValue这些 property.让人容易产生误解的是 DOM 对象也存在 checked, selected, value 这些 property, 这导致了很多人认为标签的 checked attribute 对应的是 checked property, 这是不对的.

    <input type="checkbox" checked="checked">
    defaultChecked: true

四、 js 和 jquery 提供的操作 attribue 和 property 的方法

  1. 对于 attribute, js 提供了 getAttribute(), jquery 提供了 attr() 方法; 对于 property, DOM 对象可以通过 对象名.属性名 来访问, jquery 中可以通过 prop() 方法
<body>
    <input id="test" type="checkbox" checked="checked">     
   <script>
      // attribute 操作
      var dom = document.getElementById('test');
       // 输出checkbox
       console.log(dom.getAttribute('type'));
       // 输出checkbox
       console.log($('#test').attr('type'));
   </script>    
</body>
<body>
    <input id="test" type="checkbox" checked="checked">     
   <script>
      // property 操作
      var dom = document.getElementById('test');
       // 输出checkbox
       console.log(dom.getAttribute('type'));
       // 输出checkbox
       console.log($('#test').attr('type'));
   </script>    
</body>

  1. 对于 checked, selected, value 这类 boolean attribute, 当使用 attr() 方法改变其 property 时, 对应标签的 attribute 是不会变化的. 因为它们不是相对应的.例如在 jquery 中将下面 input 的checked 状态变为 false 之后, 标签中的
    checked=“checked” 值不会发生改变, 仍然为 checked=“checked”.
<body>
    <input id="test" type="checkbox" checked="checked">     
   <script>
       $('input').prop('checked', false);
   </script>    
</body>  

JS 判断 checkbox 选中的方法

    // 判读是否选中
    if ( elem.checked )
    if ( $( elem ).prop( "checked" ) )
    if ( $( elem ).is( ":checked" ) )

五、参考

jquery中attr方法
jquery中prop方法
jquery中data方法
html中disabled的值
html中boolean属性

知识共享许可协议
本作品采用知识共享署名 4.0 国际许可协议进行许可。

猜你喜欢

转载自blog.csdn.net/m0_37890535/article/details/85528704