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

问题描述:

jqGrid中是否存在一个事件来在添加新行后执行操作?如何在添加新行后在jqGrid中执行操作

我在jqGrid wiki中看到afterInsertRow中有事件,但显然只要jqGrid在显示表格时“插入”行到表中就触发它。

那么当用户“插入”(保存)新行后我想要做些什么时,应该使用什么?或者,是否有任何可以让我“知道”新行被添加的变量?

+0

您应该更确切地描述您使用哪种“插入”。例如,你使用表单编辑。用户点击“添加”按钮,用户点击“提交”按钮后,数据将成功保存在服务器上。在收到数据成功添加的服务器响应后,您想要执行一些操作(修改服务器响应)。你从服务器发回新行的'id'还是不? – Oleg

+0

是的,用户点击“添加”按钮,填写新行数据,点击“提交”按钮,创建表中的新行。我不需要修改服务器响应。在这种特殊情况下,我只需要使用setSelection方法选择表中的第一行,但是如果添加了新行,则需要防止该行为。这就是为什么我要为此寻找事件。 – cincplug

+0

而且我有从服务器发送的行ID。 – cincplug

主要的问题是,要能够选择你需要知道新行的id的行。在大多数情况下,id将由您将数据保存在服务器上的数据库生成。因此,对服务器代码的第一个要求是在“add”操作的服务器响应中的新行上返回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至少有两个缺点。

  1. 如果使用使用网格排序的数据(jqGrid的的sortname参数不为空)网格的行会不正确排序后的新行会被添加作为第一个或最后一个行在网格中。
  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]; 
    } 
}); 

在新添加的行会电网的重载后选择的情况。

+0

感谢您的全面解答。最后我用第二种解决方案做到了。 – cincplug

+0

@cincplug:不客气!我认为这个问题对其他人很有趣,所以我对你的问题+1。 – Oleg

+0

非常感谢,希望它会:) – cincplug