jquery 全选
jQuery 实现全选功能
使用 jQuery 实现全选功能通常涉及监听全选复选框的点击事件,并根据其状态设置其他复选框的选中状态。
HTML 结构示例
<input type="checkbox" id="selectAll"> 全选
<div class="item-list">
<input type="checkbox" class="item"> 选项1
<input type="checkbox" class="item"> 选项2
<input type="checkbox" class="item"> 选项3
</div>
jQuery 代码实现

$('#selectAll').click(function() {
$('.item').prop('checked', $(this).prop('checked'));
});
$('.item').click(function() {
if ($('.item:checked').length === $('.item').length) {
$('#selectAll').prop('checked', true);
} else {
$('#selectAll').prop('checked', false);
}
});
实现原理
-
全选控制
监听全选复选框的点击事件,当被点击时获取其选中状态,并将该状态同步到所有子项复选框。 -
子项控制全选状态
监听每个子项复选框的点击事件,检查所有子项是否都被选中。如果是,则设置全选复选框为选中状态;否则取消全选复选框的选中状态。
注意事项
- 使用
prop()方法而非attr()方法操作复选框的选中状态,因为prop()更可靠且性能更好。 - 如果页面内容是动态加载的,需要使用事件委托(
on()方法)来绑定事件。
动态内容示例
$(document).on('click', '#selectAll', function() {
$('.item').prop('checked', $(this).prop('checked'));
});
$(document).on('click', '.item', function() {
if ($('.item:checked').length === $('.item').length) {
$('#selectAll').prop('checked', true);
} else {
$('#selectAll').prop('checked', false);
}
});
扩展功能
如果需要实现部分选中时全选复选框显示不确定状态(indeterminate),可以通过以下代码实现:
$('.item').click(function() {
const checkedCount = $('.item:checked').length;
const totalCount = $('.item').length;
$('#selectAll').prop('indeterminate', checkedCount > 0 && checkedCount < totalCount);
$('#selectAll').prop('checked', checkedCount === totalCount);
});






