我非常了解这个问题。我同意当前可以使用的predefined formatter('showlink' 和 'link' 格式化程序)都不够灵活。
我可以向您推荐另一种格式化程序,您可以下载here。格式化程序的使用非常简单:
{label: "AddToCart", name: "Addtocrt_addtocrt", formatter: "dynamicLink",
formatoptions: {
url: function (cellValue, rowId, rowData) {
return '/Store/AddToCart' + rowId + '?' +
$.param({
quantity: rowData.Stocks_valkogus
});
}
}
}
定义为函数的url 将在<a> 中用作href 属性的值。
除了urlformatoptions,'dynamicLink'格式化程序支持target选项(与'showlink'相同),cellValue也可以是函数和onClick回调@987654337 @、iRow、iCol、cellValue、e 作为参数。如果定义了onClick 回调,url 的值将被忽略。所以可以跳过格式化程序选项url的定义。
The demo 演示 'dynamicLink' 格式化程序的用法:
您可以在下面找到formatter: 'dynamicLink' 的当前代码:
/*global jQuery */
(function ($) {
'use strict';
/*jslint unparam: true */
$.extend($.fn.fmatter, {
dynamicLink: function (cellValue, options, rowData) {
// href, target, rel, title, onclick
// other attributes like media, hreflang, type are not supported currently
var op = {url: '#'};
if (typeof options.colModel.formatoptions !== 'undefined') {
op = $.extend({}, op, options.colModel.formatoptions);
}
if ($.isFunction(op.target)) {
op.target = op.target.call(this, cellValue, options.rowId, rowData, options);
}
if ($.isFunction(op.url)) {
op.url = op.url.call(this, cellValue, options.rowId, rowData, options);
}
if ($.isFunction(op.cellValue)) {
cellValue = op.cellValue.call(this, cellValue, options.rowId, rowData, options);
}
if ($.fmatter.isString(cellValue) || $.fmatter.isNumber(cellValue)) {
return '<a' +
(op.target ? ' target=' + op.target : '') +
(op.onClick ? ' onclick="return $.fn.fmatter.dynamicLink.onClick.call(this, arguments[0]);"' : '') +
' href="' + op.url + '">' +
(cellValue || ' ') + '</a>';
} else {
return ' ';
}
}
});
$.extend($.fn.fmatter.dynamicLink, {
unformat: function (cellValue, options, elem) {
var text = $(elem).text();
return text === ' ' ? '' : text;
},
onClick: function (e) {
var $cell = $(this).closest('td'),
$row = $cell.closest('tr.jqgrow'),
$grid = $row.closest('table.ui-jqgrid-btable'),
p,
colModel,
iCol;
if ($grid.length === 1) {
p = $grid[0].p;
if (p) {
iCol = $.jgrid.getCellIndex($cell[0]);
colModel = p.colModel;
colModel[iCol].formatoptions.onClick.call($grid[0],
$row.attr('id'), $row[0].rowIndex, iCol, $cell.text(), e);
}
}
return false;
}
});
}(jQuery));
我打算把formatter的代码和其他一些插件放到github上的jqGrid。
更新:Free jqGrid 扩展了formatter: "showlink" 的选项(请参阅the wiki article 和the answer)。所以在使用免费 jqGrid 的情况下不需要使用formatter: "dynamicLink"。