2014-07-23

jQuery 设置复选框选中状态的 BUG

Views: 16023 | 3 Comments

在以前, 如果想做一个全选和全不选的功能, 用 jQuery 非常简单, 就是设置 checked 属性. 但今天见鬼了, 以前能正常工作的代码无论如何也不能工作.

if(selectAll){
	$('input.cb').attr('checked', 'checked');
}else{
	$('input.cb').removeAttr('checked');
}

这段代码只能工作一次, 但我可以发誓, 这段代码以前用得没问题! 然后我尝试这段代码:

$('input.cb').attr('checked', selectAll);

也是只能工作一次.

后来, 终于查明好像是 jQuery 的版本兼容问题, 我找出了下面的正确方法, 但不知道是不是兼容所有版本的 jQuery.

$('input.cb').prop('checked', cb.checked);

兼容所有版本的正确方法:

// 兼容所有版本的正确方法
$('input.cb').each(function(i, e){
	e.checked = cb.checked;
});

搜索了一下, jQuery 对于 attr()prop() 有很大的争论.

Related posts:

  1. jQuery BlockUI 页面遮挡插件
  2. 获取动态加载的图片大小的正确方法
  3. jQuery延时绑定事件(lazy-bind)
  4. 如何让 PHP json_encode 函数不转义中文?
  5. [转]300+Jquery, CSS, MooTools 和 JS的导航菜单
Posted by ideawu at 2014-07-23 10:20:51 Tags:

3 Responses to "jQuery 设置复选框选中状态的 BUG"

  • 对于表单元素,attr() 取的是属性默认值,prop()可以获取当前状态值;
    attr()只能取属性值类型为string的,prop() 没有这个限制;
    h5的时代,表单元素新增是checked, disabled, required属性,这些属性的值是boolean类型,用prop()get,set肯定没问题的

    "Where both a property and an attribute with the same name exists, usually updating one will update the other, but this is not the case for certain attributes of inputs, such as value and checked: for these attributes, the property always represents the current state while the attribute (except in old versions of IE) corresponds to the default value/checkedness of the input (reflected in the defaultValue / defaultChecked property)" Reply
    @a06062125: 解释得太多了, 我没发现区分 property 和 attribute 有任何实际的意义. Reply
  • 我觉得后来加入的 prop 是为了更加规范 api 的一致性。从 1.6 版本新增 prop,the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.将原先的 attr 一部分功能移到 prop 上来。
    老是说,我很喜欢这个改动,太棒了。 Reply

Leave a Comment