超链接/按钮在jqGrid中如何调用自定义函数

5
我想在jqgrid的每一行中添加一个超链接/按钮,触发自定义的javascript函数。经过多次尝试后仍然没有成功。
jQuery('#ProductListGrid').jqGrid({
    url: '/Product/ProductListGrid',
    datatype: 'json',
    multiselect: true,
    height: 250,
    autowidth: true,
    mtype: 'GET',
    loadComplete: addlinks,
    colNames: ['ProductId', 'ProductName', 'edit'],
    colModel: [
      { name: 'ProductId', index: 'ProductId',key:true, width: 70, hidden: true, editable: true, size: 5 },
      { name: 'ProductName', index: 'ProductName', width: 70, editable: true },
      { name: 'edit', index: 'edit', width: 70},

    ],
    pager: jQuery('#ProductListGrid_pager'),
});
function addlinks() {
    var ids = jQuery("#ProductListGrid").getDataIDs();
    alert(ids);
    for (var i = 0; i < ids.length; i++) {
        be = "<a href='#' style='height:25px;width:120px;' type='button' title='Slet' onclick=\"ff()\" >Slet</>";
        jQuery("#ProductListGrid").jqGrid('setCell', ids[i],'edit','', { act: be });
    }
    //for (var i = 0; i < ids.length; i++) {
    //    jQuery("#ProductListGrid").setCell(i, 'edit', '<a href="#">edit</edit>');
    //}
}
function ff()
{
    alert("hi");
}

addlinks函数中的代码正在执行,但是该列中没有任何内容显示。我尝试使用自定义格式化,但无法显示自定义文本“编辑”,而链接点击也无法触发js方法。

你尝试过使用formatter吗?如果是的话,能否分享一下或提供demo - GGG
我在网格中添加了另一列,显示链接 { name: 'ProductId',formatter: 'showlink',formatoptions: { baseLinkUrl: '/Product/ProductEdit/',addParam: '&action=edit' } }。 - Krishna Sarma
1
我建议您阅读这个答案这个答案,其中展示了如何使用1)自定义格式化程序将一些文本/链接/按钮放置在“编辑”列中,以及2)如何使用beforeSelectRow回调而不是onclick属性来在单击链接/按钮时执行任何JavaScript代码... - Oleg
beforeSelectRow回调函数有第二个参数e,它提供了有关所单击元素的信息。 $(e.target).closest("td")将是单击的单元格,$(e.target).closest("tr")将是单击的行,$(e.target).closest("td").attr("id")将是行ID等等。 var iCol = $.jgrid.getCellIndex($(e.target).closest("td")[0]);是单击单元格的列号。无论如何,我强烈建议您使用gridview:true选项(请参见答案)以提高性能。使用addlinks会使网格变慢。 - Oleg
1个回答

9
您需要像下面这样调用编辑列的格式化程序:
在最后一列添加formatter: addLink
colModel: [
      { name: 'ProductId', index: 'ProductId',key:true, width: 70, hidden: true, editable: true, size: 5 },
      { name: 'ProductName', index: 'ProductName', width: 70, editable: true },
      { name: 'edit', index: 'edit', width: 70,formatter: addLink},

    ]

添加 JavaScript 函数:

function addLink(cellvalue, options, rowObject) 
{
  //to get row Id
  alert(options.rowId);
  // to get product Id
  alert(rowObject.ProductId);
  return "<a href='#' style='height:25px;width:120px;' type='button' title='Slet' onclick=\"ff()\" >Slet</a>";
}

更多有关格式化程序的信息在此处


谢谢,这会触发该方法。你能帮我如何将id传递给函数吗? - Krishna Sarma
你想把productId传递给ff函数吗? - Bhushan Kawadkar
是的,还需要产品ID和行ID,以防需要其他信息。 - Krishna Sarma
1
在addLink函数中,您可以使用rowObject像rowObject.ProductId或rowObject.ProductName一样访问当前行的任何列。 - Bhushan Kawadkar
请使用选项来获取行 ID,例如 options.rowId。 - Bhushan Kawadkar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接