本帖最后由 Xiexian 于 2023-6-13 09:32 编辑
js实现全选框-全选-全不选-反选-联动选项的功能
[JavaScript] 纯文本查看 复制代码 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
window.onload = function(){
let Oall = document.getElementById("all");
let Ounall = document.getElementById("unall");
let Oinvert = document.getElementById("invert");
let OA = document.getElementById("Asd");
let Obox = document.getElementById('box');
let Oinp = Obox.getElementsByTagName("input");
let i;
//全选按钮事件
Oall.onclick = function(){
for(i = 0; i<Oinp.length; i++){
Oinp[i].checked = true;
}
OA.checked = true;
}
//全不选按钮事件
Ounall.onclick = function(){
for(i = 0; i<Oinp.length; i++){
Oinp[i].checked = false;
}
OA.checked = false;
}
//全部反选按钮事件
Oinvert.onclick = function(){
for(i = 0; i<Oinp.length; i++){
Oinp[i].checked = !Oinp[i].checked;
}
let count = 0;
for(i = 0; i<Oinp.length; i++){
if(Oinp[i].checked){
count++;
}
}
if(count == Oinp.length){
OA.checked = true;
}else{
OA.checked = false;
}
}
//全选复选框事件
OA.onclick = function(){
for(i =0; i<Oinp.length; i++){ //如果全选被选中,则下列全部勾选
Oinp[i].checked = OA.checked;
}
}
// debugger;
//复选框勾选
for(i = 0; i<Oinp.length; i++){
Oinp[i].onclick = function(){ //这是刷新页面的原因:事件发生了
let count = 0; //用于计数,如果count==Oinp.length那么全部选中
for(i = 0; i<Oinp.length; i++){
if(Oinp[i].checked){
count++;
}
}
if(count == Oinp.length){
OA.checked = true;
}else{
OA.checked = false;
}
}
}
}
</script>
<input type="checkbox" id="Asd">全选
<hr>
<input type="button" value="all" id="all">
<input type="button" value="unall" id="unall">
<input type="button" value="invert" id="invert">
<hr>
<div id="box">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</div>
</body>
</html> |