我想你的代码 $(".deleteRowButton").button({icons: {primary: 'ui-icon-trash'}, text: false}); 没有工作,因为你把它放在了错误的地方。如果您在gridComplete 内部创建<button class='deleteRowButton' ...>,您应该在您发布的代码之后直接调用$(".deleteRowButton").button(...) 也inside of gridComplete:
gridComplete: function () {
var $this = $(this), ids = $this.jqGrid('getDataIDs'), l = ids.length,
i, deleteButton;
for (i = 0; i < l; i++) {
deleteButton = "<button type='button' style='height:22px;width:20px;'" +
" class='deleteRowButton' title='Delete' onclick=deleteRow(" +
ids[i] + ")></button>";
$this.jqGrid('setRowData', ids[i], { DeleteButton: deleteButton });
}
$(".deleteRowButton").button({
icons: {
primary: 'ui-icon-trash'
},
text: false
});
}
见the first demo。
上述方法的性能存在小问题。使用setRowData 在页面上进行更改。页面上的每次更改都会重新计算页面上存在的所有其他元素的位置。因此,为了提高性能,建议减少网格上的更改次数。所以更好的方法是使用custom formattrer。新版本的代码实际上将与前一个版本一样简单。您只需将formatter 定义为函数:
{ name: 'DeleteButton', width: 20,
formatter: function (cellvalue, options) {
return "<button type='button' class='deleteRowButton' " +
"style='height: 22px;width: 20px;' title='Delete'></button>";
}},
并将gridComplete或loadComplete的代码缩减为
gridComplete: function () {
$(".deleteRowButton").button({
icons: {
primary: 'ui-icon-trash'
},
text: false
}).click(function (e) {
var $tr = $(e.target).closest("tr.jqgrow");
alert("the row with id=" + $tr.attr("id") + " need be deleted");
});
}
在您的原始代码中,方法deleteRow 必须是全局(它应该在顶层定义)。新代码只能使用click 事件处理程序。见the next demo。
顺便说一句,您实际上并不需要将每个 <button> 绑定到 click 事件处理程序。众所周知,如果按钮上没有click 事件处理程序,则会发生event bubbling。因此,不必每次在加载和重新加载网格时绑定click 事件处理程序,只需在整个网格体上定义一次相应的事件处理程序。换句话说,您可以使用onCellSelect 回调。使用起来很舒服,因为rowid 和单击单元格的列的索引已经计算过了。此外,根据onCellSelect 回调的第4 个参数e,您可以访问事件处理程序,其中e.tagret 是单击的<button> 的DOM 元素。所以可以将上面gridComplete的代码替换成如下代码:
onCellSelect: function (rowid, iCol, cellcontent, e) {
if ($(e.target).closest("button.deleteRowButton").length > 0) {
alert("the row with id=" + rowid + " need be deleted");
}
},
gridComplete: function () {
$(".deleteRowButton").button({
icons: {
primary: 'ui-icon-trash'
},
text: false
});
}
这样可以进一步提高性能并减少页面使用的内存。 The demo 实时显示最后的代码。在大多数情况下,您不需要使用像 $(e.target).closest("button.deleteRowButton").length > 0 这样的结构。取而代之的是,您只需验证列索引iCol。如果需要,您可以改为测试列名。你可以使用
$(this).jqGrid("getGridParam", "colModel")[iCol].name
将iCol 转换为对应的列名。