
本文介绍如何在 w2ui grid 中基于业务逻辑动态禁用部分行的选择能力,同时保留其他行的正常多选功能,核心是利用 `onselect` 事件结合 `event.preventdefault()` 精准拦截非法选择。
在使用 w2ui Grid 开启 multiSelect: true 后,所有行默认均可被选中。但实际业务中常需根据数据状态(如记录是否已锁定、是否为只读项等)限制某些行不可选。w2ui 并未提供内置的 disabledRows 配置项,但可通过监听 onSelect 事件实现灵活控制。
关键在于:在 onSelect 回调中判断当前被点击的记录是否允许选择;若不允许,则调用 event.preventDefault() 阻止默认选中行为。注意该事件会在每次点击选择列(checkbox)或按 Ctrl/Cmd + 点击行时触发,且 event.recid 可准确获取目标记录 ID。
以下为完整可运行示例:
<link href="https://cdn.jsdelivr.net/npm/w2ui@2.0/dist/w2ui-2.0.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/w2ui@2.0/dist/w2ui-2.0.min.js"></script>
<div id="grid" style="height: 500px;"></div>
<script>
const DISABLED_RECID_LIST = [1, 2, 6, 7]; // 明确声明禁止选择的 recid
const grid = new w2grid({
name: 'grid',
box: '#grid',
multiSelect: true,
show: {
selectColumn: true
},
columns: [
{ field: 'recid', text: 'ID', size: '10px', sortable: true, attr: 'align="center"' },
{ field: 'field', text: '内容', size: '500px', sortable: true }
],
records: [
{ recid: 1, field: 'You cannot select this' },
{ recid: 2, field: 'neither this' },
{ recid: 3, field: 'but you can select this' },
{ recid: 4, field: 'or this' },
{ recid: 5, field: 'and what do you think about this?' },
{ recid: 6, field: 'Ok no, not this one' },
{ recid: 7, field: 'as even this must be disabled' }
],
onSelect(event) {
// 检查当前被选中的记录是否在禁用列表中
if (DISABLED_RECID_LIST.includes(event.recid)) {
event.preventDefault(); // 阻止选中
w2alert(`记录 #${event.recid} 不可选择`, '操作受限');
}
}
});
</script>✅ 注意事项与最佳实践:
- onSelect 是唯一可靠拦截点——不要尝试在 onClick 或 onDblClick 中处理,它们不直接控制选择状态;
- event.preventDefault() 仅阻止本次选择动作,不影响已选中的其他行,符合多选场景预期;
- 建议将禁用规则封装为纯函数(如 isRowSelectable(recid)),便于复用和单元测试;
- 若需视觉反馈(如灰显 checkbox),可配合 render 列配置或 CSS 类动态添加(例如通过 onRender 修改 DOM);
- 注意:event.recid 在点击表头全选时为 undefined,此时若需控制全选行为,应额外判断 event.target === 'header' 并遍历 records 过滤。
通过该方案,你可在不修改 w2ui 源码的前提下,以声明式逻辑精准管控每行的选择权限,兼顾灵活性与可维护性。










