能否在jqGrid指定位置添加新行?按钮点击新增行需求咨询
jqGrid添加新行的实现方案
嘿,我来帮你搞定这两个jqGrid的需求问题~
一、实现第一行末尾ADD MORE按钮并点击添加新行到其下方
要实现这个效果,我们可以分两步走:给第一行的最后单元格渲染按钮,然后给按钮绑定点击事件添加新行。
1. 配置列的自定义格式化器
在jqGrid的colModel中,给最后一列设置自定义formatter,只在第一行显示ADD MORE按钮:
$("#yourGridId").jqGrid({ // 其他配置项... colModel: [ // 你的其他列配置,比如: { name: 'id', width: 50 }, { name: 'name', width: 150 }, // 最后一列:操作列 { name: 'actions', width: 120, formatter: function(cellvalue, options) { // 获取表格的第一行ID,判断当前行是否是第一行 const firstRowId = $("#yourGridId").jqGrid('getDataIDs')[0]; if (options.rowId === firstRowId) { return '<button class="add-more-btn">ADD MORE</button>'; } return ''; // 其他行不显示按钮 } } ] });
2. 绑定按钮点击事件添加新行
用事件委托的方式绑定按钮的点击事件,避免动态元素的事件丢失问题,然后调用addRowData方法在第一行下方插入新行:
$(document).on('click', '.add-more-btn', function() { const $grid = $("#yourGridId"); const firstRowId = $grid.jqGrid('getDataIDs')[0]; // 构造新行的数据,根据你的列name来定义 const newRowData = { id: 'new_row_' + Date.now(), // 生成唯一ID,避免重复 name: '新添加的行' // 其他列的数据... }; // 在第一行的下方插入新行,position参数用'after',参考行ID是firstRowId $grid.jqGrid('addRowData', newRowData.id, newRowData, 'after', firstRowId); });
二、jqGrid能否在指定位置添加新行?
当然可以!jqGrid的addRowData方法本身就支持指定插入位置,你只需要设置第四个参数position和第五个参数rowid(参考行的ID)即可:
position可选值:'first':插入到表格的第一行'last':插入到表格的最后一行'before':插入到指定参考行的前面'after':插入到指定参考行的后面
举几个例子:
- 在ID为
target_row_123的行前面插入新行:
$grid.jqGrid('addRowData', newRowId, newRowData, 'before', 'target_row_123');
- 在表格最后一行插入新行:
$grid.jqGrid('addRowData', newRowId, newRowData, 'last');
这样就能灵活控制新行的插入位置啦~
内容的提问来源于stack exchange,提问作者Ram
相关产品推荐
相关产品推荐

