jQuery操作checkBox(多选框)

来源:互联网 发布:淘宝寄澳洲,电话号码 编辑:程序博客网 时间:2024/06/05 00:44

问题:工作中要用到jQuery操作多选框(checkbox)的知识,就把以前记录及笔记找了出来直接用,但是问题出现了,取消选择之后,再次选中指定的多选框,用浏览器看(F12)是加上了checked属性,但是页面显示没有选中(没有打勾),这里把解决问题的方法总结一下。

下面给出一种解决方案(使用的jQuery版本2.1.3):

1、静态页面CheckBox.html(注意:必须要在check标签里面加上select属性)

<!DOCTYPE html><html><head><meta charset="utf-8"><title>jQuery操作ChecBox的用法</title><script type="text/javascript" src="js/jquery.min.js" ></script><script type="text/javascript" src="js/CheckBox.js" ></script></head><body><input type="checkbox" name="checkBox1" value="1" checked="true">1</input><input type="checkbox" name="checkBox1" value="2" checked="true">2</input><input type="checkbox" name="checkBox1" value="3" checked="true">3</input><input type="checkbox" name="checkBox1" value="4" checked="true">4</input><input type="checkbox" name="checkBox1" value="5" checked="true">5</input><input type="checkbox" name="checkBox1" value="6" checked="true">6</input><input type="checkbox" name="checkBox1" value="7" checked="true">7</input><input type="checkbox" name="checkBox1" value="8" checked="true">8</input><input type="checkbox" name="checkBox1" value="9" checked="true">9</input></body><div><input type="button" value="全选"/ onclick="selectAll()"><input type="button" value="反选" onclick="fanXuan()"/><input type="button" value="取消选择" onclick="cancelSelect()"/></div></html>
2、js文件 多选、取消选择和反选(CheckBox.js)

function selectAll(){$("input[name='checkBox1']").each(function(){  $(this).prop("checked",true);});}function fanXuan(){$("input[name='checkBox1']").each(function(){if($(this).prop("checked") == true){    $(this).prop("checked",false);}else{    $(this).prop("checked",true);}});}function cancelSelect(){$("input[name='checkBox1']").each(function(){  $(this).prop("checked",false);});}
这里使用的时prop属性,下面分析一下原因,为了避免重造轮子,大家可以到下面两篇文章看一下:

参考文章1:jquery中attr和prop的区别

参考文章2:jquery中attr方法和prop方法的区别

0 0