在有列的网格中工作,它依赖于另一个列,这是常见的情况。所以我试着对你的问题做出详细的回答。
首先,您可以通过以下简单方式实现您的要求:您可以使用editRow 的aftersavefunc 选项在修改行之后进行一些自定义操作。例如,您可以重新计算"TotalMarks" 列的新值,并以{TotalMarks: newValue} 作为参数显式调用setRowData。
另一方面,通常在"TotalMarks" 列上使用custom formatter 来制作“虚拟”列,哪个值不在源数据中,但哪个值将根据其他列的值计算出来.如果您只需要定义相应的自定义格式化程序,并且如果您使用本地数据类型,请定义自定义sorttype(请参阅the answer、this one 和this one)。如果您使用数据编辑,那么您应该不要忘记定义unformat (unformatter function)。
The following demo 演示了这种方法。它有"total" 列,其内容计算为"amount" 和"tax" 列的内容之和。输入数据不包含 "total" 列的任何值。 "total" 列是可编辑的,但由于 editoptions: { disabled: "disabled" } 选项,用户无法直接更改值:
"total"对应的定义是
{ name: "total", width: 60, template: numberTemplate,
sorttype: function (cellValue, rowObject) {
return parseFloat(rowObject.amount) + parseFloat(rowObject.tax);
},
formatter: function (cellValue, options, rowObject) {
var total = parseFloat(rowObject.amount) + parseFloat(rowObject.tax);
return $.fn.fmatter.call(this, "currency", total, options);
},
unformat: function (cellValue, options, cell) {
// make copy of options
var opt = $.extend(true, {}, options);
// change opt.colModel to corresponds formatter: "currency"
opt.colModel.formatter = "currency";
delete opt.colModel.unformat;
// unformat corresponds to formatter "currency"
return $.unformat.call(this, cell, opt);
},
editoptions: { disabled: "disabled" } }
顺便说一下,我使用onSelectRow的如下代码来实现内联编辑:
onSelectRow: function (rowid) {
var $self = $(this),
// savedRows array is not empty if some row is in inline editing mode
savedRows = $self.jqGrid("getGridParam", "savedRow");
if (savedRows.length > 0) {
$self.jqGrid("restoreRow", savedRows[0].id);
}
$self.jqGrid("editRow", rowid, { keys: true });
}
如何看到代码不使用任何lastSel 变量,如the well known code example。如果在一个 HTML 页面上使用多个可编辑的网格,这可能是实用的。
如果不想让"total" 列可编辑,可以使用aftersavefunc 强制重新计算total:
onSelectRow: function (rowid) {
var $self = $(this),
// savedRows array is not empty if some row is in inline editing mode
savedRows = $self.jqGrid("getGridParam", "savedRow");
if (savedRows.length > 0) {
// cancel editing of the previous selected row if it was in editing state.
// jqGrid hold intern savedRow array inside of jqGrid object,
// so it is safe to call restoreRow method with any id parameter
// if jqGrid not in editing state
$self.jqGrid("restoreRow", savedRows[0].id);
}
$self.jqGrid("editRow", rowid, {
keys: true,
aftersavefunc: function (rowid) {
var $this = $(this),
rowObject = $this.jqGrid("getGridParam", "datatype") === "local" ?
$this.jqGrid("getLocalRow", rowid) :
{
amount: $this.jqGrid("getCell", rowid, "amount"),
tax: $this.jqGrid("getCell", rowid, "tax")
};
// one ca call setRowData below with two properties
// only which are required for
$this.jqGrid("setRowData", rowid, {
amount: rowObject.amount,
tax: rowObject.tax,
total: "dummy"
});
}
});
}
"total" 列有editable: false 属性而不是editoptions: { disabled: "disabled" },编辑看起来更舒服