jqGrid自定义格式化类型
可以对指定的列定义自定义格式化函数。注意配置这个值可以为函数名称,不能用引号括起或者以()结束,如格式化函数名称为func,不能配置formatter为"func"或者func(),直接func即可,可以直接配置一个匿名函数,示例
jQuery("#grid_id").jqGrid({ // ... colModel: [ // ... {name:'price', index:'price', width:60, align:"center", editable: true, formatter:currencyFmatter}, // ... ] // ... }); function currencyFmatter (cellvalue, options, rowObject) { // do something here return new_format_value }
定义和参数
自定格式化函数参数如下
function myformatter ( cellvalue, options, rowObject ) { // format the cellvalue to new format return new_formated_cellvalue; }
这个函数需要返回一个值。参数说明
-
cellvalue:需要格式的原始值
-
options : 为一个对象,格式如 { rowId: rid, colModel: cm} 1)rowId:此行的id 2)colModel:jqGrid配置的colModel
-
rowObject:包含此行数据的对象。jqGrid中设置datatype为xml/xmlstring,则为xml行的节点,依据xmlReader配置的规则。datatype为json,则为键值对,依据jsonReader配置的规则。
Unformatting
之前提到的预定义格式化类型章节所有预定义类型和编辑模式是兼容的,就是说数字,链接和email等需要转换,才能使他们被正确编辑。当使用自定义格式化函数使,获取数据的方法(如getRowData 或 getCell),要使用反格式化以便获取到原始值。
现在的问题是,使用了自定义格式化函数后,如何在编辑模式下或者调用getRowData 或 getCell方法时获取原始的内容。
答案就是:你可以使用自定义的unformatter 函数来处理,可以在colModel中配置这个值。
看下面的示例,显示image对象和编辑image的路径
jQuery("#grid_id").jqGrid({ ... colModel: [ ... {name:'price', index:'price', width:60, align:"center", editable: true, formatter:imageFormat, unformat:imageUnFormat}, ... ] ... }); function imageFormat( cellvalue, options, rowObject ){ return '<img src="'+cellvalue+'" />'; } function imageUnFormat( cellvalue, options, cell){ return $('img', cell).attr('src'); }
-
cellvalue :被格式化处理过的内容,需要被还原为原始值
-
options : 为一个对象,格式如 { rowId: rid, colModel: cm} 1)rowId:此行的id 2)colModel:jqGrid配置的colModel
-
cellobject :jQuery包装过的单元格对象(is a jQuery cell object.,通过后面的说法应该是cell DOM对象,没有包装过的)。通过这个对象可以获取到想要的内容,例如 调用 jQuery(cellobject).html()得到单元格内的html代码。
示例
下面的示例模拟部分currency格式化通过自定义格式化函数和 unformat 函数
jQuery("#grid_id").jqGrid({ ... colModel: [ ... {name:'price', index:'price', width:60, align:"center", editable: true, formatter:currencyFmatter, unformat:unformatCurrency}, ... ] ... }); function currencyFmatter (cellvalue, options, rowObject) { return "$"+cellvalue; } function unformatCurrency (cellvalue, options) { return cellvalue.replace("$",""); }
如果grid中的内容为123.00,那么显示在单元格中的内容为: $123.00;当使用getRowData 或者 getCell方法或者任何一种编辑模式,那么此列的值将被转为 123.00。
创建通用格式化函数
有些时候你需要在很多地方使用自定义的format/unformat 函数代码。你可以按照上面的例子那样来定义。但是,我们设计了格式化模块,开发者可以扩展它使开发过程更加简单。下面我们将讨论如何使自定义的format/unformat 函数对所有代码可用。
加载了jqGrid核心代码后,你可以其后添加一个script标签定义通用的格式化函数(或者创建一个js文件,然后倒入进来也行)
jQuery.extend($.fn.fmatter , { currencyFmatter : function(cellvalue, options, rowdata) { return "$"+cellvalue; } }); jQuery.extend($.fn.fmatter.currencyFmatter , { unformat : function(cellvalue, options) { return cellvalue.replace("$",""); } });
然后在代码中可以这样使用
jQuery("#grid_id").jqGrid({ //... colModel: [ //... {name:'price', index:'price', width:60, align:"center", editable: true, formatter:'currencyFmatter'}, //... ] //... });
此示例中不再需要制定unformat函数。
来源:http://www.trirand.com/jqgridwiki/doku.php?id=wiki:custom_formatter
加支付宝好友偷能量挖...
原创文章,转载请注明出处:jqGrid自定义格式化类型