jquery全选
jQuery 实现全选功能的方法
使用 jQuery 实现全选功能通常涉及监听全选复选框的点击事件,并根据其状态设置其他复选框的选中状态。以下是几种常见的实现方式:
基础全选功能
监听全选复选框的 change 事件,通过 prop() 方法设置其他复选框的选中状态。

$('#selectAll').change(function() {
$('.itemCheckbox').prop('checked', $(this).prop('checked'));
});
反选功能扩展
在全选基础上增加反选逻辑,当部分复选框未选中时,取消全选复选框的选中状态。

$('#selectAll').change(function() {
$('.itemCheckbox').prop('checked', $(this).prop('checked'));
});
$('.itemCheckbox').change(function() {
var allChecked = $('.itemCheckbox').length === $('.itemCheckbox:checked').length;
$('#selectAll').prop('checked', allChecked);
});
动态生成复选框的处理
对于动态生成的复选框,使用事件委托确保事件绑定有效。
$(document).on('change', '#selectAll', function() {
$('.itemCheckbox').prop('checked', $(this).prop('checked'));
});
$(document).on('change', '.itemCheckbox', function() {
var allChecked = $('.itemCheckbox').length === $('.itemCheckbox:checked').length;
$('#selectAll').prop('checked', allChecked);
});
表格中的全选功能
在表格中实现全选功能,通常针对某一列的复选框进行操作。
$('#selectAll').change(function() {
$('table tbody input[type="checkbox"]').prop('checked', $(this).prop('checked'));
});
$('table tbody input[type="checkbox"]').change(function() {
var allChecked = $('table tbody input[type="checkbox"]').length === $('table tbody input[type="checkbox"]:checked').length;
$('#selectAll').prop('checked', allChecked);
});
注意事项
- 确保选择器准确匹配目标复选框,避免误操作其他元素。
- 动态生成的元素需要使用事件委托绑定事件。
- 考虑性能优化,避免在大量复选框场景下频繁操作 DOM。
以上方法可根据实际需求进行调整,适应不同的应用场景。






