方法1 name
<body>
<script type="text/javascript" language="javascript">
function check(){
var oo=document.getElementsByName("pro"); //通過.getElementsByName()把name為“pro”的復(fù)選框定義成集合
for(var i=0;i<oo.length;i++){
oo[i].checked=document.getElementById("all").checked; //當(dāng)id為“all”的復(fù)選框被選中時(shí),讓集合中每一個(gè)對象都被選中
}
}
</script>
<input type="checkbox" id="all" onclick="check();" />全選
<input name="pro" type="checkbox" id="1" />蘋果
<input name="pro" type="checkbox" id="2" />梨
<input name="pro" type="checkbox" id="3" />香蕉
</body>
方法2 class
<!DOCTYPE html>
<html>
<head>
<title>全選復(fù)選框</title>
</head>
<body>
<h1>全選復(fù)選框</h1>
<input type="checkbox" id="selectAll"> 全選
<input type="checkbox" class="checkbox"> 選項(xiàng)1
<input type="checkbox" class="checkbox"> 選項(xiàng)2
<input type="checkbox" class="checkbox"> 選項(xiàng)3
<input type="checkbox" class="checkbox"> 選項(xiàng)4
<script>
const selectAllCheckbox = document.querySelector("#selectAll");
const checkboxes = document.querySelectorAll(".checkbox");
selectAllCheckbox.addEventListener("change", function() {
const isChecked = this.checked;
checkboxes.forEach((checkbox) => {
checkbox.checked = isChecked;
});
});
</script>
</body>
</html>
方法3使用jQuery實(shí)現(xiàn)
<!DOCTYPE html>
<html>
<head>
<title>全選復(fù)選框</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>全選復(fù)選框</h1>
<input type="checkbox" id="selectAll"> 全選
<input type="checkbox" class="checkbox"> 選項(xiàng)1
<input type="checkbox" class="checkbox"> 選項(xiàng)2
<input type="checkbox" class="checkbox"> 選項(xiàng)3
<input type="checkbox" class="checkbox"> 選項(xiàng)4
<script>
(".checkbox").prop("checked", isChecked);
});
</script>
</body>
</html>