jquery.attr更改input元素checked状态

本文详细介绍了在使用jQuery进行全选/取消全选功能时遇到的问题,包括属性检查和代码调整的过程。通过对比原始代码与优化后的代码,解释了如何避免undefined值并确保功能正确实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

$("#choice").bind("change",function(){
        $("input[type='checkbox']").attr("checked", $("#choice").attr("checked"));
});

   使用上述代码最全选/取消全选时发现,$("#choice").attr("checked")报告undefined,于是将控制元素设置上属性checked,这是发现无论如何,$("#choice").attr("checked")的值都为true。于是查阅http://api.jquery.com/attr/发现其中有如下描述:

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 checked, 
selected, or disabled state of form elements, use the .prop() method.

   于是调整代码如下:

$("#choice").bind("change",function(){
        $("input[type='checkbox']").prop("checked", $("#choice").prop("checked"));
});

   在firefox、opera、safari、chrome、IE7-9中测试通过。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值