如何在启用multiSelect的w2ui grid中禁用指定行的选中功能?
实现w2ui Grid部分行禁用选中权限的方案
完全可以实现仅允许部分记录被选中的需求,以下是具体的实现方案:
核心思路
通过给目标记录标记自定义属性,结合w2ui Grid的事件拦截机制,阻止禁用行的选中操作,同时可添加视觉样式提示用户。
完整代码示例
let grid = new w2grid({ name: 'grid', box: '#grid', multiSelect: true, show: { selectColumn: true }, columns: [ { field: 'recid', text: 'recid', size: '10px', sortable: true, attr: 'align="center"' }, { field: 'field', text: 'field', size: '500px', sortable: true }, ], records: [ { recid: 1, field: '你无法选中此行', noSelect: true }, { recid: 2, field: '此行也无法选中', noSelect: true }, { recid: 3, field: '但你可以选中此行' }, { recid: 4, field: '还有此行' }, { recid: 5, field: '那此行呢?当然可以选中' }, { recid: 6, field: '不行,此行不能选', noSelect: true }, { recid: 7, field: '此行同样禁用选中', noSelect: true }, ], // 拦截选中事件,阻止禁用行被选中 onSelect: function(event) { const record = this.get(event.recid); if (record.noSelect) { event.preventDefault(); return false; } }, // 给禁用行添加视觉样式,提升用户体验 onRender: function(event) { const record = this.get(event.recid); if (record.noSelect) { event.row.style.backgroundColor = '#f5f5f5'; event.row.style.cursor = 'not-allowed'; } }, // 处理全选逻辑,跳过禁用行 onSelectAll: function(event) { event.preventDefault(); this.records.forEach(record => { if (!record.noSelect) { this.select(record.recid); } }); } })
<link href="https://cdn.jsdelivr.net/npm/w2ui@2.0.0/w2ui-2.0.min.css" rel="stylesheet"/> <script src="https://cdn.jsdelivr.net/npm/w2ui@2.0.0/w2ui-2.0.min.js"></script> <div id='grid' style='height:500px'></div>
方案说明
- 标记禁用行:给需要禁止选中的记录添加自定义属性
noSelect: true,作为识别依据 - 拦截选中操作:通过
onSelect事件,判断当前行是否为禁用行,若是则调用event.preventDefault()阻止默认选中行为 - 视觉提示:利用
onRender事件给禁用行添加灰色背景和禁止光标样式,让用户直观感知该行不可选 - 全选处理:重写
onSelectAll事件,取消默认全选逻辑,仅选中未标记noSelect的记录
内容的提问来源于stack exchange,提问作者Stefano Radaelli
相关产品推荐
相关产品推荐

