jQuery.js实现全选反选重选功能

jQuery.js实现全选反选重选功能

在这里插入图片描述
HTML代码如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<button id="quanxun">全选</button> <button id="fanxuan">反选</button> <button id="buxuan">重新选</button>
		<p><input type="checkbox"  data-id="1" /></p>
		<p><input type="checkbox"  data-id="2"  /></p>
		<p><input type="checkbox"  data-id="3"  /></p>
		<p><input type="checkbox"  data-id="4" /></p>
		<p><input type="checkbox"  data-id="5" /></p>
		<p><input type="checkbox"  data-id="6" /></p>
	</body>
</html>

js代码如下:
说明:arrays = [];此数组是向后端发送的数据

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
	
	let arrays = [];
	//	全选
	$("#quanxun").click(function(){
		$("p input").prop('checked',true);
		for (var i = 0; i < $("p input").length; i++) {
			arrays.push($("p input").eq(i).data('id'));
		}
		
		console.log(arrays)
	})
	
	//	反选
	$("#fanxuan").click(function(){
		arrays = [];
		for (var i = 0; i < $("p input").length; i++) {
			if($("p input").eq(i).is(':checked')){
				$("p input").eq(i).prop("checked", false)
			}
			else{
				$("p input").eq(i).prop("checked", true)
			}
		}		
		for (var i = 0; i < $("p input").length; i++) {
			if($("p input").eq(i).is(':checked')){
				arrays.push($("p input").eq(i).data('id'));
			}
			
		}
		
		console.log(arrays)
	})
	
	//	重选
	$("#buxuan").click(function(){
		$("p input").prop('checked',false);
		arrays = [];
		console.log(arrays)
	})
	
	//	单个值变化时
	$("p input").change(function(){
		arrays = [];
		if($(this).is(':checked')){
			$(this).prop("checked", true)
		}else{
			$(this).prop("checked", false)
			
		}
		for (var i = 0; i < $("p input").length; i++) {
			if($("p input").eq(i).is(':checked')){
				arrays.push($("p input").eq(i).data('id'));
			}
			if($("p input").eq(i).prop("checked") == false){
				arrays.splice(i,1)
			}
		}
		console.log(arrays)
	})
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_42208679

生命不息,写作不止,求打赏!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值