Syncfusion(ES5 Javascript)可编辑网格按选中产品更新同行其他字段的方法
实现思路
你使用的是Syncfusion EJ2 Grid的Batch批量编辑模式,只需在产品下拉框的change事件中,拿到选中产品对应的Rate、IsTaxable配置,调用Grid的setRowData方法更新当前编辑行的对应字段即可,同时要避免使用全局变量存储下拉框实例导致的多行编辑冲突。
前提说明
你的产品数据源productDDLSource的每条数据需要包含对应产品的rate、isTaxable字段,示例结构如下:
const productDDLSource = [ { productId: 1, product: "电脑", rate: 5999, isTaxable: true }, { productId: 2, product: "打印纸", rate: 29, isTaxable: false } ];
修改后的完整代码
// 移除全局的productElem、productDDL变量,避免多行编辑冲突 ej.grids.Grid.Inject(ej.grids.Edit, ej.grids.Toolbar); var grid = new ej.grids.Grid({ dataSource: [], toolbar: ['Add', 'Cancel', 'Update'], // 增加Update按钮支持批量保存 editSettings: { showConfirmDialog: true, showDeleteConfirmDialog: true,allowEditing: true, allowAdding: true, allowDeleting: true, mode: 'Batch' }, columns: [ { field: 'Product', headerText: 'Product', type: 'string', foreignKeyField: "ProductId", foreignKeyValue: "Product", edit: { create: function () { // 直接创建元素返回,不需要全局存储 return document.createElement('input'); }, read: function (args) { // 从当前元素的下拉实例读取值 return args.ej2_instances[0].text; }, destroy: function (args) { // 销毁当前行的下拉实例 if(args.ej2_instances[0]) args.ej2_instances[0].destroy(); }, write: function (args) { // 直接用args.element作为下拉挂载容器,不需要全局变量 const productDDL = new ej.dropdowns.ComboBox({ fields: { text: 'product', value: 'product' }, dataSource: productDDLSource, placeholder: "Select a Product", allowFiltering: true, filtering: (e) => { if (!e.text || e.text.length < 3) { return; } else { var query = new ej.data.Query().addParams("searchText",e.text.trim()); e.updateData(productDDLSource, query); } }, change: (e) => { const selectedProduct = e.selectedData; if(!selectedProduct) return; // 核心逻辑:更新当前行对应字段 grid.setRowData(args.rowIndex, { Rate: selectedProduct.rate, IsTaxable: selectedProduct.isTaxable, // 可选配置:自动计算Total,不需要可删除 Total: selectedProduct.rate * (args.rowData.Quantity || 1) }); } }); productDDL.appendTo(args.element); }, } }, { field: 'Rate', headerText: 'Rate', type: 'number' }, { field: 'Quantity', headerText: 'Quantity', type: 'number' }, { field: 'Total', headerText: 'Total', type: 'number' }, { field: 'IsTaxable', headerText: 'Is Taxable', type: 'checkbox' } ], height: 315 }); grid.appendTo('#grid');
补充说明
setRowData方法会自动将修改同步到Grid的批量编辑缓存中,用户点击批量保存按钮时会统一提交所有变更,完全符合Batch编辑模式的交互逻辑。如果需要修改Quantity时也自动更新Total,只需监听Grid的cellEdit事件,判断修改字段为Quantity时重新计算Total值更新即可。
内容的提问来源于stack exchange,提问作者Prabesh
相关产品推荐
相关产品推荐

