您的位置:首页 > 运维架构

attr和prop的区别-解决checkbox选中不起作用的问题

2016-07-14 09:19 429 查看
        今天在写checkbox的全选,半全选时遇到了一个问题,刚开始点击全选按钮时,可以全选,再点击可以全部清除选中,再点击就不起作用了?

        我打开审查元素发现,第三次点击应该是全选的状态,这时里面的属性确实都是“checked=checked”但是checkbox却没显示选中,然后就查了一下;

我用的是attr(“checked”,true);后来把attr改成了prop就可以了;所以理解attr和prop很重要;

        

从 jQuery 1.6 开始新增了一个方法 prop(),但是一直都没有使用过。

从中文意思看,两者分别是获取/设置 attributes 和 properties 的方法,那么为什么还要增加 prop() 方法呢?
Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior.


因为在 jQuery 1.6 之前,使用 attr() 有时候会出现不一致的行为。

那么,什么时候使用attr(),什么时候使用prop()?
To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.


根据官方的建议:具有 true 和 false 两个属性的属性,如 checked, selected 或者 disabled 使用prop(),其他的使用 attr()

到此,将 attr('checked') 改成 prop('checked') 即可修复提的 issues 了。

部分内容转载至:http://wenzhixin.net.cn/2013/05/24/jquery_attr_prop 文翼的博客
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jquery