You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在启用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>

方案说明

  1. 标记禁用行:给需要禁止选中的记录添加自定义属性noSelect: true,作为识别依据
  2. 拦截选中操作:通过onSelect事件,判断当前行是否为禁用行,若是则调用event.preventDefault()阻止默认选中行为
  3. 视觉提示:利用onRender事件给禁用行添加灰色背景和禁止光标样式,让用户直观感知该行不可选
  4. 全选处理:重写onSelectAll事件,取消默认全选逻辑,仅选中未标记noSelect的记录

内容的提问来源于stack exchange,提问作者Stefano Radaelli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 03:05:29