jQuery操作checkBox(多选框)

问题:工作中要用到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="全选"/ οnclick="selectAll()">
		<input type="button" value="反选" οnclick="fanXuan()"/>
		<input type="button" value="取消选择" οnclick="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方法的区别

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值