attr和prop

<div class="content-item active">
              <table class="table">
                <thead>
                  <tr>
                    <th></th>
                    <th>姓名</th>
                    <th>部门</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td><input type="checkbox" /></td>
                    <td>小雷</td>
                    <td>信息化管理部</td>
                  </tr>
                  <tr>
                    <td><input type="checkbox" /></td>
                    <td>小雷</td>
                    <td>信息化管理部</td>
                  </tr>
                  <tr>
                    <td><input type="checkbox" /></td>
                    <td>小雷</td>
                    <td>信息化管理部</td>
                  </tr>
                </tbody>
              </table>
            </div>
 1 $('.content-item').on('click','table tr',function(){
 2         var $this=$(this);
 3         var CheckBox=$this.find('input[type=checkbox]');
 4         if(CheckBox.prop('checked')==true){
 5           CheckBox.prop('checked',false);
 6         }else{
 7           CheckBox.prop('checked',true);
 8         }
 9         console.log(CheckBox.prop('checked'));
10       })

想要的效果是点击tr其中的复选框变换状态。

一开始用的是attr

 1 $('.content-item').on('click','table tr',function(){
 2         var $this=$(this);
 3         var CheckBox=$this.find('input[type=checkbox]');
 4         if(CheckBox.attr('checked')==true){
 5           CheckBox.attr('checked',false);
 6         }else{
 7           CheckBox.attr('checked',true);
 8         }
 9         console.log(CheckBox.attr('checked'));
10       });
View Code

输出的全是 checked;

改成判断为状态checked

$('.content-item').on('click','table tr',function(){
        var $this=$(this);
        var CheckBox=$this.find('input[type=checkbox]');
        if(CheckBox.attr('checked')=='checked'){
          CheckBox.removeAttr('checked');
        }else{
          CheckBox.attr('checked','checked');
        }
        console.log(CheckBox.attr('checked'));
      });
View Code

输出的是checked undefined。。。

朋友说试下prop,结果就好了。

然后搜索一下资料,目前很认同,记录一下

  • 对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
  • 对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。

像checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此需要使用prop方法去操作才能获得正确的结果。

第二大段代码中的第五行用的

 CheckBox.prop('checked',false);而不是和removeAttr类似的removeProp()这是因为:
window对象或DOM元素的一些内置属性是不允许删除的,如果试图删除这些属性,将会导致浏览器产生一个错误。jQuery首先会将该属性的值赋为undefined,并忽略掉浏览器生成的任何错误信息
所以不要使用
removeProp()来删除DOM元素的本地属性checkedselecteddisabled。这将彻底删除对应的属性,并且,一旦删除之后,你无法再向该DOM元素重新添加对应的属性。可以使用prop()函数将其设为false即可,例如:jQueryObject.prop("checked", false)
原文地址:https://www.cnblogs.com/MissBean/p/attr_and_prop.html