奇葩问题——jquery操作checkbox的 checked属性

最近做checkbox,遇到一个奇葩问题,如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-1.9.1.js"></script>
</head>
<body>
    <input type="button" value="all" id="selall">

    <input type="checkbox" name="sel[]" value="1">1
    <input type="checkbox" name="sel[]" value="2">2
    <input type="checkbox" name="sel[]" value="3">3
<script type="text/javascript">
$(function(){
    var chk = false,
        sel = $('input[name^="sel"]');
    $('#selall').click(function(){
        if(chk){
            chk = false;
            sel.attr('checked', false);
        }else{
            chk = true;
            sel.attr('checked', true);
        }
    })
})
</script>
</body>
</html>

以上代码chrome中,点击button 全选,再点击全不选。一切正常,但是第三次点击,就罢工了。F12查看,发现checked属性是修改了的,就是说添加了  checed="checked",但是未显示勾。

检查代码,没有问题啊。难道是兼容问题,于是换了firefox,问题依旧。之后又换了IE,居然正常了!! 没错IE正常,这是要逆袭的节奏?不能啊……于是查看jquery API,在.attr()中中间一点,吐槽完IE后,有这么一段话

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checkedselected, or disabled state of form elements, use the .prop() method.

Attributes vs. Properties

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr()method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr()retrieves attributes.

就是说jquery 1.6+,使用attr(),获取未定义的属性将返回undefined .检索和修改DOM的特性(property), 如表单元素的checked,selected,或disabled状态,使用prop()方法

于是替换attr()为prop(),简化下代码 改为:

var sel = $('input[name^="sel"]');
$('#selall').click(function(){
    if(! $(this).prop('checked')){            
        sel.prop('checked', false);
    }else{           
        sel.prop('checked', true);
    }
})


最后,吐槽下! IE你果然是个大坑……

转载于:https://my.oschina.net/u/1391970/blog/223239

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值