方法1 name
<body>
<script type="text/javascript" language="javascript">
function check(){
var oo=document.getElementsByName("pro"); //通过.getElementsByName()把name为“pro”的复选框定义成集合
for(var i=0;i<oo.length;i++){
oo[i].checked=document.getElementById("all").checked; //当id为“all”的复选框被选中时,让集合中每一个对象都被选中
}
}
</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>全选复选框</title>
</head>
<body>
<h1>全选复选框</h1>
<input type="checkbox" id="selectAll"> 全选
<input type="checkbox" class="checkbox"> 选项1
<input type="checkbox" class="checkbox"> 选项2
<input type="checkbox" class="checkbox"> 选项3
<input type="checkbox" class="checkbox"> 选项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实现
<!DOCTYPE html>
<html>
<head>
<title>全选复选框</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>全选复选框</h1>
<input type="checkbox" id="selectAll"> 全选
<input type="checkbox" class="checkbox"> 选项1
<input type="checkbox" class="checkbox"> 选项2
<input type="checkbox" class="checkbox"> 选项3
<input type="checkbox" class="checkbox"> 选项4
<script>
(".checkbox").prop("checked", isChecked);
});
</script>
</body>
</html>