jquery复选框全选反选
jQuery 复选框全选与反选实现
使用 jQuery 可以轻松实现复选框的全选和反选功能。以下是几种常见的实现方式:

全选功能实现
$('#selectAll').click(function() {
$('input[type="checkbox"]').prop('checked', $(this).prop('checked'));
});
这段代码会监听 ID 为 selectAll 的复选框的点击事件,当它被选中时,页面上所有的复选框都会被选中;取消选中时,所有复选框也会被取消选中。

反选功能实现
$('#reverseSelect').click(function() {
$('input[type="checkbox"]').each(function() {
$(this).prop('checked', !$(this).prop('checked'));
});
});
这段代码会遍历所有复选框,将它们的状态取反(选中变未选中,未选中变选中)。
完整示例代码
<!DOCTYPE html>
<html>
<head>
<title>复选框全选反选</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<input type="checkbox" id="selectAll">全选<br>
<input type="button" id="reverseSelect" value="反选"><br>
<input type="checkbox" class="item">选项1<br>
<input type="checkbox" class="item">选项2<br>
<input type="checkbox" class="item">选项3<br>
<script>
$('#selectAll').click(function() {
$('.item').prop('checked', $(this).prop('checked'));
});
$('#reverseSelect').click(function() {
$('.item').each(function() {
$(this).prop('checked', !$(this).prop('checked'));
});
});
</script>
</body>
</html>
注意事项
- 使用
prop()方法而不是attr()方法来操作复选框的选中状态,因为prop()更可靠 - 可以为特定组的复选框添加相同的 class,以便只操作特定组的复选框
- 全选复选框的状态可以根据子复选框的状态自动更新
高级实现:自动更新全选状态
$('.item').change(function() {
var allChecked = $('.item').length === $('.item:checked').length;
$('#selectAll').prop('checked', allChecked);
});
这段代码会在任一子复选框状态改变时检查是否所有子复选框都被选中,并相应更新全选复选框的状态。






