如何在添加新行后在jqGrid中执行操作

cin*_*lug 6 jquery jqgrid

jqGrid中是否有一个事件在添加新行后执行操作?

我在jqGrid wiki中看到有事件afterInsertRow,但显然只要jqGrid在显示表时"插入"行到表,就会触发它.

那么在用户"插入"(保存)新行后我想做什么时应该使用什么?或者,是否有任何变量可以让我"知道"添加了新行?

Ole*_*leg 4

主要问题是为了能够选择行,您需要知道新行的 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);
    }
});
Run Code Online (Sandbox Code Playgroud)

在评论部分,afterComplete我展示了如何使用jQuery UI 高亮效果来突出显示新添加的行(请参阅旧答案)。它可以替代行的选择。您还可以使用选择和突出显示效果。

该选项reloadAfterSubmit: false至少有两个缺点。

  1. 如果在网格中使用排序数据(sortnamejqGrid 参数不为空),则在将新行添加为网格中的第一行或最后一行后,网格的行将无法正确排序。
  2. 如果网格已经具有每页最大行数(由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];
    }
});
Run Code Online (Sandbox Code Playgroud)

在这种情况下,重新加载网格后将选择新添加的行。