js实现多选
实现多选功能
在JavaScript中实现多选功能可以通过多种方式完成,常见场景包括表格多选、列表多选或复选框组多选。以下是几种典型实现方法:
复选框组多选
通过监听复选框的change事件,记录选中项的value或自定义属性:
document.querySelectorAll('.checkbox-item').forEach(checkbox => {
checkbox.addEventListener('change', function() {
const selectedValues = Array.from(document.querySelectorAll('.checkbox-item:checked'))
.map(item => item.value);
console.log('当前选中:', selectedValues);
});
});
HTML结构示例:
<input type="checkbox" class="checkbox-item" value="option1"> Option 1
<input type="checkbox" class="checkbox-item" value="option2"> Option 2
表格行多选
为表格添加全选/单选功能,通常结合data-*属性存储关键信息:
// 行点击事件
document.querySelectorAll('table tbody tr').forEach(row => {
row.addEventListener('click', (e) => {
if (e.target.tagName !== 'INPUT') {
const checkbox = row.querySelector('input[type="checkbox"]');
checkbox.checked = !checkbox.checked;
triggerSelectionUpdate();
}
});
});
// 全选控制
document.getElementById('selectAll').addEventListener('change', function() {
const checkboxes = document.querySelectorAll('table tbody input[type="checkbox"]');
checkboxes.forEach(cb => cb.checked = this.checked);
});
function triggerSelectionUpdate() {
const selectedRows = Array.from(document.querySelectorAll('table tbody input[type="checkbox"]:checked'))
.map(cb => cb.closest('tr').dataset.id);
console.log('选中行ID:', selectedRows);
}
HTML结构示例:
<table>
<thead><tr><th><input type="checkbox" id="selectAll"></th></tr></thead>
<tbody>
<tr data-id="1"><td><input type="checkbox"></td></tr>
</tbody>
</table>
列表项多选(Shift连续选择)
实现类似文件管理器的连续多选交互:
let lastSelected = null;
document.querySelectorAll('.selectable-item').forEach(item => {
item.addEventListener('click', function(e) {
if (e.shiftKey && lastSelected) {
const items = Array.from(document.querySelectorAll('.selectable-item'));
const start = items.indexOf(lastSelected);
const end = items.indexOf(this);
items.slice(Math.min(start, end), Math.max(start, end) + 1)
.forEach(el => el.classList.add('selected'));
} else {
this.classList.toggle('selected');
}
lastSelected = this;
});
});
CSS样式建议:
.selectable-item.selected { background-color: #e3f2fd; }
虚拟列表优化
对于大规模数据渲染,使用虚拟列表技术避免DOM性能问题:
// 基于窗口滚动事件计算可见项
window.addEventListener('scroll', () => {
const scrollTop = document.documentElement.scrollTop;
const visibleItems = getVisibleItems(scrollTop);
renderItems(visibleItems);
});
function handleItemSelection(itemId) {
// 维护一个Set存储选中项
selectedItems.has(itemId)
? selectedItems.delete(itemId)
: selectedItems.add(itemId);
}
注意事项
- 状态管理:复杂场景建议使用
Set或Map存储选中项,避免重复 - 无障碍访问:为复选框添加
<label>关联,确保键盘可操作 - 性能优化:大数据量时使用事件委托代替单个监听
- 框架实现:React/Vue等框架可通过状态驱动实现更简洁的多选逻辑







