How to use "formatter" dynamically in jqGrid.Is it possible?

时间:2016-07-11 22:05:26

标签: javascript jquery jqgrid jqgrid-formatter mvcjqgrid

Is there a way to dynamically use the "formatter" in jqGrid?I want to make use of formatTitle function from the code dynamically, Here is my code:

HTML

<table id="list47"><tr><td></td></tr></table>
<div id="plist47"></div>

Javascript:

var md=[{ "id": "83123a", Name: "Name 1", "PackageCode": "83123a" },
                { "id": "83432a", Name: "Name 3", "PackageCode": "83432a" },
                { "id": "83566a", Name: "Name 2", "PackageCode": "83566a" }]

var he=["id","Name","PackageCode"];
var c=[];

for(var i=0;i<he.length;i++){

  c.push('{"name":"'+he[i]+'","index":"'+he[i]+'"}');
}
var colmodel="["+c+"]"

//var colmodel= [{name:'id', index:'id', width:55},
         //     {name:'Name', index:'Name' },
          //      {name:'PackageCode', index:'PackageCode'}]

  // c.push('{"name":"'+he[i]+'","index":"'+he[i]+'"'+'"formatter":'+formatTitle+'}');                  
jQuery("#list47").jqGrid({
    //data: md,
    datatype: "local",
    height: 150,
    rowNum: 10,
    colNames: he,
    colModel: jQuery.parseJSON(colmodel),
    rowList: [10,20,30],
    pager: "#plist47",
    viewrecords: true,
     caption: "json data grid"
});
for(var i=0;i<md.length;i++){
 jQuery("#list47").addRowData(i+1,md[i]);
 }

  function formatTitle(cellValue, options, rowObject) {
                return "<a href='" + rowObject.Link + "'>" + cellValue.substring(0, 45) + "..." + "</a>";
                //return cellValue.substring(0, 50) + "...";
            };

1 个答案:

答案 0 :(得分:0)

您必须将格式化程序放在字符串中,如下所示

for(var i=0;i<he.length;i++){
 c.push('{"name":"'+he[i]+'","index":"'+he[i]+'"'+',"formatter":"formatTitle"'+'}'); 
}

然后在jqGrid代码之前定义格式化程序,如下所示

  $.fn.fmatter.formatTitle = function (cellValue, options, rowObject) {
     return "<a href='" + rowObject.Link + "'>" + cellValue.substring(0, 45) + "..." + "</a>";         
    };

因为它是用字符串包装的(格式化程序:“formatTitle”),所以你不能使用以前的签名来格式化

function formatTitle(cellValue,options,rowObject)如果格式化程序:formatTitle无法动态构造,则可以使用

以下是您问题的 jsfiddle解决方案