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>