一、功能实现核心知识点
- jQuery 选择器:通过
$('selector')
精准选取复选框元素 - 属性操作:使用
prop('checked', boolean)
设置 / 获取复选框选中状态 - 事件绑定:通过
on('event', callback)
监听用户操作 - 集合遍历:利用
each()
方法遍历复选框集合 - 数据过滤:通过
:checked
选择器筛选已选中的复选框
二、全选功能实现方案
1. 基础 HTML 结构
html
预览
<div class="checkbox-group">
<input type="checkbox" id="select-all" class="check-all"> 全选
<div class="checkbox-list">
<input type="checkbox" class="item-checkbox" value="1"> 选项1<br>
<input type="checkbox" class="item-checkbox" value="2"> 选项2<br>
<input type="checkbox" class="item-checkbox" value="3"> 选项3<br>
<input type="checkbox" class="item-checkbox" value="4"> 选项4<br>
</div>
</div>
2. jQuery 全选代码实现
javascript
$(function() {
// 全选/全不选功能
$('#select-all').on('change', function() {
const isChecked = $(this).prop('checked');
// 批量设置所有子复选框的选中状态
$('.item-checkbox').prop('checked', isChecked);
});
// 子复选框变化时更新全选框状态
$('.item-checkbox').on('change', function() {
const allCheckboxes = $('.item-checkbox');
const checkedCount = allCheckboxes.filter(':checked').length;
// 全选状态判断
if (checkedCount === allCheckboxes.length) {
$('#select-all').prop('checked', true);
} else if (checkedCount > 0) {
// 半选状态(需配合CSS样式)
$('#select-all').prop('indeterminate', true);
} else {
$('#select-all').prop({
checked: false,
indeterminate: false
});
}
});
});
3. 半选状态优化(CSS 实现)
css
.check-all:indeterminate {
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12"><rect width="12" height="12" fill="none" stroke="currentColor" stroke-width="2"/></svg>');
background-repeat: no-repeat;
background-position: center;
background-size: 10px;
}
三、选中项查询功能实现
1. 获取选中项值数组
javascript
function getSelectedValues() {
// 使用:checked选择器过滤选中的复选框
const selectedItems = $('.item-checkbox:checked');
const values = [];
// 遍历收集value值
selectedItems.each(function() {
values.push($(this).val());
});
return values;
}
// 示例调用
const selectedValues = getSelectedValues();
console.log('选中项值:', selectedValues);
2. 获取选中项文本内容
javascript
function getSelectedTexts() {
const selectedItems = $('.item-checkbox:checked');
const texts = [];
selectedItems.each(function() {
// 获取复选框后的文本内容(需根据实际HTML结构调整)
const text = $(this).next('span, br').text().trim() || $(this).parent().text().trim();
texts.push(text);
});
return texts;
}
3. 批量操作选中项(示例:禁用选中项)
javascript
function disableSelected() {
$('.item-checkbox:checked').prop('disabled', true);
}