attr和prop

时间:2023-03-08 23:56:19
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>
 $('.content-item').on('click','table tr',function(){
var $this=$(this);
var CheckBox=$this.find('input[type=checkbox]');
if(CheckBox.prop('checked')==true){
CheckBox.prop('checked',false);
}else{
CheckBox.prop('checked',true);
}
console.log(CheckBox.prop('checked'));
})

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

一开始用的是attr

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

输出的全是 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'));
});

输出的是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)