使用jQuery Kendo UI Grid选中行内多单元格求和并展示为新列方法问询
完全可以实现该需求,以下是具体实现方案:
实现思路
- 配置Kendo UI Grid开启单元格多选模式,支持跨列选中
- 提前在Grid列配置中预留求和结果列,用于展示每行选中列的数值求和结果
- 监听Grid的选中变更事件,每次选中范围调整时,遍历所有行计算选中列的数值和,更新到对应行的求和列中
核心代码示例
$("#grid").kendoGrid({ dataSource: { data: [ { id: 1, 语文: 90, 数学: 85, 英语: 92, 选中列总分: 0 }, { id: 2, 语文: 78, 数学: 92, 英语: 86, 选中列总分: 0 }, { id: 3, 语文: 95, 数学: 76, 英语: 89, 选中列总分: 0 } ], schema: { model: { id: "id", fields: { 语文: { type: "number" }, 数学: { type: "number" }, 英语: { type: "number" }, 选中列总分: { type: "number" } } } } }, // 开启多单元格选中模式 selectable: "multiple cell", columns: [ { field: "语文", title: "语文" }, { field: "数学", title: "数学" }, { field: "英语", title: "英语" }, // 独立求和结果列,设置为不可编辑 { field: "选中列总分", title: "选中列总分", editable: false } ], // 选中状态变更触发求和逻辑 change: function(e) { const grid = this; // 获取所有选中单元格的列索引并去重 const selectedColIndexes = [...new Set([...grid.select()].map(cell => grid.cellIndex(cell)))]; // 遍历所有行计算求和 grid.dataItems().forEach(row => { let total = 0; selectedColIndexes.forEach(colIndex => { const field = grid.columns[colIndex].field; // 仅对数值字段求和,非数值默认计为0 if (field && typeof row[field] === "number") { total += row[field]; } }); // 自动更新UI展示最新求和结果 row.set("选中列总分", total); }); } });
拓展优化
- 如果需要支持点击列头一键选中整列,可以额外绑定列头点击事件,点击时自动选中该列所有单元格即可
- 若选中列包含非数值类型列,可在求和逻辑中增加过滤规则,跳过非数值列避免计算错误
- 如需动态新增求和列而非提前预留,可以调用Grid的
setOptions方法动态修改columns配置添加结果列
内容的提问来源于stack exchange,提问作者Binary
相关产品推荐
相关产品推荐

