主要问题是要能够选择行,您需要知道新行的 id。在大多数情况下,id 将由您在服务器上保存数据的数据库生成。因此,对服务器代码的第一个要求是在“添加”操作的服务器响应中返回新行的 id。
例如,您的服务器代码返回您所在行的 ID 作为“添加”操作的响应。
$("#list").jqGrid('navGrid', '#pager', {/*navGrid options*/}, {/*Edit optoins*/}, {
/*Add options:*/
reloadAfterSubmit: false,
afterSubmit: function (response) {
return [true, '', response.responseText];
},
addedrow: "last", // add new row at the end of grid
afterComplete: function (response, postdata) {
// this.gbox is the string like "#gbox_list"
var gridId = this.gbox.substr(6);
//if (postdata.oper === "add") {
// // highlight the new "added" row
// var row = $("#" + $.jgrid.jqID(postdata.id));
// row.effect("highlight", {}, 3000);
//}
$('#' + gridId).jqGrid('setSelection', postdata.id);
}
});
在afterComplete 的评论部分,我展示了如何使用jQuery UI highlight 效果突出显示新添加的行(请参阅the old answer)。它可以替代行的选择。您还可以同时使用选择和突出显示效果。
reloadAfterSubmit: false 选项至少有两个缺点。
- 如果在网格中使用已排序的数据(jqGrid 的
sortname 参数不为空),则在将新行添加为第一行或作为网格中的最后一行。
- 如果网格已经有每页的最大行数(由
rowNum 参数定义),则添加新行将跟随每页行数过多的网格。
所以你可以执行以下操作
var idToSelect;
$("#list").jqGrid({
// ... all jqGrid options
loadComplete: function () {
if (idToSelect) {
$(this).jqGrid('setSelection', idToSelect);
//$("#" + $.jgrid.jqID(idToSelect)).effect("highlight", {}, 3000);
idToSelect = undefined;
}
}
}).jqGrid('navGrid', '#pager', {/*navGrid options*/}, {/*Edit optoins*/}, {
/*Add options:*/
afterSubmit: function (response) {
// save the id of new row. If the format of the data returned from
// the server is different you should change the next row
// corresponds to the returned data. For example if the server returns
// back JSON data in the form {"myId":"123"} you should use
// $.parseJSON(response.responseText).myId
// instead of response.responseText below
idToSelect = response.responseText;
return [true, '', response.responseText];
}
});
如果新添加的行将在重新加载网格后被选中。