我将从自定义格式化程序开始。 jqGrid 支持predefined formatters,如formatter: "integer"、formatter: "date"。您可以“注册”您的 custom formatter 和 unformatter 作为您可以使用的另一个值。例如,如果要注册formatter: "myCheckbox",则需要将$.fn.fmatter.myCheckbox 定义为格式化函数,将$.fn.fmatter.myCheckbox.unformat 定义为解格式化函数。
$.extend($.fn.fmatter, {
myCheckbox: function (cellValue, options, rowObject) {
// the code of the custom formatter is here
...
}
});
$.extend($.fn.fmatter.myCheckbox, {
unformat: function (cellValue, options, elem) {
// the code of the custom unformatter is here
...
}
});
here 的代码使用 Font Awesome 4.x 并注册新的formatter: "checkboxFontAwesome4"。 “注册”自定义格式化程序可以简化您的代码。
下一个功能。 jqGrid 从 jqGrid 3.8.2 版开始支持列模板(参见the old answer)。它允许您将colModel 中使用的通用设置 定义为一个对象,并在colModel 中使用template 属性。例如,如果您有许多包含数字的列,您可以将 numberTemplate 对象定义为
var numberTemplate = {
formatter: "number", align: "right", sorttype: "number", width: 60,
searchoptions: {
sopt: ["eq", "ne", "lt", "le", "gt", "ge"]
}
};
然后您可以将树列"tax"、"amount" 和"total" 定义为
colModel: [
...
{ name: "tax", template: numberTemplate },
{ name: "amount", template: numberTemplate },
{ name: "total", width: 70, template: numberTemplate },
...
]
在您定义列的方式中,numberTemplate 中的所有属性都将应用于列。在numberTemplate 中定义的默认width: 60 将被覆盖为“total”列的值width: 70。
列模板的使用允许您在代码模板中为日期定义 once,例如使用 jQuery UI Datepicker 并在项目的每个网格的每一列中使用相应的参考模板。
github 上当前版本的 jqGrid 支持将模板“注册”为字符串。所以下一个版本(4.6.0 以上),我希望很快发布,将支持以下语法:
$.extend($.jgrid, {
cmTemplate: {
myNumber: {
formatter: "number", align: "right", sorttype: "number",
searchoptions: { sopt: ["eq", "ne", "lt", "le", "gt", "ge"] }
}
}
});
(在示例中我没有在模板中包含width)
colModel: [
...
{ name: "tax", width: 52, template: "number" },
{ name: "amount", width: 75, template: "number" },
{ name: "total", width: 60, template: "number" },
....
]
详情请见the pull request。