码迷,mamicode.com
首页 > Web开发 > 详细

jQuery的attr方法和prop方法的区别及相关bug处理

时间:2016-05-14 18:46:58      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

以下是jQuery API文档对attr方法和prop方法的概述:

attr(name|properties|key,value|fn):Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.(获取匹配元素集合中的第一个元素的属性值,或为每一个匹配元素设置一个或多个属性)

prop(name|properties|key,value|fn):Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element.(获取匹配元素集合中的第一个元素的属性值,或为每一个匹配元素设置一个或多个属性)

纳尼?!!!这不是坑我吗,官网给出两种方法的解释几乎相差无几,在以前,一般操作元素的属性值时,我都用attr,直至出现了一个神奇的bug,见以下代码:

$(‘.member_grounp_list li‘).on(‘click‘,function(){
  $this = $(this);
  var _check = $this.find(‘.edit_check‘);
  if(_check.attr(‘checked‘)){
    _check.arrr(‘checked‘,false);
  }else{
    _check.attr(‘checked‘,true);
  }
});

以上代码是对<li>标签绑定了点击事件切换<li>标签里面的chekbox的checked属性,这个时候,神奇的bug就出现了,连续点击<li>标签之后,checkbook只有在第一轮中正确表现出选中和取消选中后,以后checkbook对事件都毫无反应。

接着,我对代码加入打印事件,查看是否是事件只运行到一轮就失效了。

$(‘.member_grounp_list li‘).on(‘click‘,function(){
  $this = $(this);
  var _check = $this.find(‘.edit_check‘); 
  if(_check.attr(‘checked‘)){
    _check.arrr(‘checked‘,false);
    console.log(‘0‘);
  }else{
    _check.attr(‘checked‘,true);
    console.log(‘1‘);
  }
});

继续连续点击<li>标签,控制台能成功连续切换打印出"0"和"1",然而checkbox经过第一轮后,在表现上依然是一直处于没选中的状态。此时的我一脸懵逼==

google一下,才想起了prop这个方法,对于表单元素自身特有属性操作时,应该使用prop方法。马上改过来试试。

$(‘.member_grounp_list li‘).on(‘click‘,function(){
  $this = $(this);
  var _check = $this.find(‘.edit_check‘); 
  if(_check.prop(‘checked‘)){
    _check.prop(‘checked‘,false);
  }else{
    _check.prop(‘checked‘,true);
  }
});

再一次连续点击测试,OK,通过,BUG解决。

总结:对于表单元素特有属性的操作时,应该使用prop方法。而对于其他属性操作,则基本靠attr方法就可以解决。

 

jQuery的attr方法和prop方法的区别及相关bug处理

标签:

原文地址:http://www.cnblogs.com/herofei/p/5493033.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!