jquery全选反选
jQuery全选反选实现方法
使用jQuery实现全选和反选功能可以通过操作复选框的checked属性来完成。以下是几种常见的实现方式:
基础全选/反选实现
// 全选
$('#selectAll').click(function() {
$('.itemCheckbox').prop('checked', true);
});
// 反选
$('#invertSelect').click(function() {
$('.itemCheckbox').each(function() {
$(this).prop('checked', !$(this).prop('checked'));
});
});
带联动效果的全选
// 全选复选框联动
$('#selectAll').click(function() {
var isChecked = $(this).prop('checked');
$('.itemCheckbox').prop('checked', isChecked);
});
// 单项选择时检查全选状态
$('.itemCheckbox').click(function() {
var allChecked = $('.itemCheckbox').length === $('.itemCheckbox:checked').length;
$('#selectAll').prop('checked', allChecked);
});
表格中的全选/反选
// 表格全选
$('#tableSelectAll').click(function() {
$('table tbody input[type="checkbox"]').prop('checked', $(this).prop('checked'));
});
// 表格反选
$('#tableInvertSelect').click(function() {
$('table tbody input[type="checkbox"]').each(function() {
$(this).prop('checked', !$(this).prop('checked'));
});
});
带计数功能的选择
// 更新选择计数
function updateSelectedCount() {
var selectedCount = $('.itemCheckbox:checked').length;
$('#selectedCount').text(selectedCount);
}
// 绑定复选框变化事件
$('.itemCheckbox').change(updateSelectedCount);
// 全选时也更新计数
$('#selectAll').change(function() {
$('.itemCheckbox').prop('checked', $(this).prop('checked'));
updateSelectedCount();
});
注意事项
- 确保为全选复选框和单项复选框设置了正确的class或ID选择器
- 使用
prop()方法而不是attr()来操作checked属性 - 对于大量复选框操作时,考虑性能优化
- 事件委托可用于动态生成的复选框元素
以上方法可以根据实际需求进行组合和调整,以适应不同的应用场景。







