复选框 checkbox 选中事件

 项目中用的jquery-1.11 今天需要检测一个checkbox的选中状态,想当然的用 .attr("checked") ,结果发现,无论是否选中,这个值都是 undefined 未定义。

 折腾了半天,发现:As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop()method.

 注意最后两句话,说什么.attr() 不能用于普通对象,数组,窗口,文档什么玩意的,要重新获取改变dom属性,用.prop()方法。

 另外:checked属性在页面初始化的时候已经初始化好了,不会随着状态的改变而改变。所以如果checkbox一开始是选中的,那么返回的是checked,如果一开始没被选中,则返回的是undefined

 结果:prop()可用

 复选框 全选/反选

  

遍历checkbox,判断是否有选中

     

原文地址:https://www.cnblogs.com/nww57/p/5007691.html