jqgrid动态列动态生成colModel和colNames

来源:互联网 发布:mac共享wifi 编辑:程序博客网 时间:2024/05/21 11:40

参考网站:http://blog.mn886.net/jqGrid/

demo下载自该网站》参数-方法-事件-文档》新手demo下载》点击此处下载此demo

在应用过程中稍作修改(只修改index.js文件):

静态colModel:

function pageInit(){var jqdata=[{"userid":01,"username":"皮皮虾","password":"biubiubiu"},{"userid":02,"username":"象拔蚌","password":"boomboomboom"}];//创建jqGrid组件jQuery("#list2").jqGrid({datatype : "json",//请求数据返回的类型。可选json,xml,txtcolNames : [ 'userid','username','password' ],//jqGrid的列显示名字colModel : [ //jqGrid每一列的配置信息。包括名字,索引,宽度,对齐方式.....             {name : 'userid',index : 'userid',width : 55},              {name : 'username',index : 'username',width : 90},              {name : 'password',index : 'password',width : 100}           ],rowNum : 10,//一页显示多少条rowList : [ 10, 20, 30 ],//可供用户选择一页显示多少条pager : '#pager2',//表格页脚的占位符(一般是div)的idsortname : 'id',//初始化的时候排序的字段sortorder : "desc",//排序方式,可选desc,ascmtype : "post",//向后台请求数据的ajax的类型。可选post,getviewrecords : true,caption : "JSON Example"//表格的标题名字});//将jqdata的值循环添加进jqGridfor (var i = 0; i <= jqdata.length; i++) {                    jQuery("#list2").jqGrid('addRowData', i + 1, jqdata[i]);                }}
效果:


动态生成:

function pageInit(){var jqdata=[{"userid":01,"username":"皮皮虾","password":"动态biubiubiu"},{"userid":02,"username":"象拔蚌","password":"动态boomboomboom"}];var names=[];var model=[];//此处因为数据源数组中的结构相同且不为空,直接遍历索引为0的数据即可$.each(jqdata[0], function(key,value) {names.push(key);model.push({name:key,index:key,width:100});});//创建jqGrid组件jQuery("#list2").jqGrid({datatype : "json",//请求数据返回的类型。可选json,xml,txtcolNames : names,//jqGrid的列显示名字colModel : model,rowNum : 10,//一页显示多少条rowList : [ 10, 20, 30 ],//可供用户选择一页显示多少条pager : '#pager2',//表格页脚的占位符(一般是div)的idsortname : 'id',//初始化的时候排序的字段sortorder : "desc",//排序方式,可选desc,ascmtype : "post",//向后台请求数据的ajax的类型。可选post,getviewrecords : true,caption : "JSON Example"//表格的标题名字});//将jqdata的值循环添加进jqGridfor (var i = 0; i <= jqdata.length; i++) {                    jQuery("#list2").jqGrid('addRowData', i + 1, jqdata[i]);                }}


效果:


重点区别在于:



遍历数据源,获取key的值,然后push进数组,在生成jqgrid时直接调用。

之前查了很多资料都是说发送请求到后台然后返回一个数组,后来确实这样试了一下,失败了,我也没去找原因,因为我感觉这种方法不大好,后来浏览jqgrid文档发现一个方法:tableToGrid();

后来查看源码是这样的(代码很长,没有兴趣就不要往下看了,是jqgrid的源码部分,作用就是将一个table转成jqgrid,我一想这就是动态生成啊,后来就根据这段源码做出了动态生成model):

function tableToGrid(selector, options) {    jQuery(selector).each(function () {        if (this.grid) { return; } //Adedd from Tony Tomov        // This is a small "hack" to make the width of the jqGrid 100%        jQuery(this).width("99%");        var w = jQuery(this).width();        // Text whether we have single or multi select        var inputCheckbox = jQuery('tr td:first-child input[type=checkbox]:first', jQuery(this));        var inputRadio = jQuery('tr td:first-child input[type=radio]:first', jQuery(this));        var selectMultiple = inputCheckbox.length > 0;        var selectSingle = !selectMultiple && inputRadio.length > 0;        var selectable = selectMultiple || selectSingle;        //var inputName = inputCheckbox.attr("name") || inputRadio.attr("name");        // Build up the columnModel and the data        var colModel = [];        var colNames = [];        jQuery('th', jQuery(this)).each(function () {            if (colModel.length === 0 && selectable) {                colModel.push({                    name: '__selection__',                    index: '__selection__',                    width: 0,                    hidden: true                });                colNames.push('__selection__');            } else {                colModel.push({                    name: jQuery(this).attr("id") || jQuery.trim(jQuery.jgrid.stripHtml(jQuery(this).html())).split(' ').join('_'),                    index: jQuery(this).attr("id") || jQuery.trim(jQuery.jgrid.stripHtml(jQuery(this).html())).split(' ').join('_'),                    width: jQuery(this).width() || 150                });                colNames.push(jQuery(this).html());            }        });        var data = [];        var rowIds = [];        var rowChecked = [];        jQuery('tbody > tr', jQuery(this)).each(function () {            var row = {};            var rowPos = 0;            jQuery('td', jQuery(this)).each(function () {                if (rowPos === 0 && selectable) {                    var input = jQuery('input', jQuery(this));                    var rowId = input.attr("value");                    rowIds.push(rowId || data.length);                    if (input.is(":checked")) {                        rowChecked.push(rowId);                    }                    row[colModel[rowPos].name] = input.attr("value");                } else {                    row[colModel[rowPos].name] = jQuery(this).html();                }                rowPos++;            });            if (rowPos > 0) { data.push(row); }        });        // Clear the original HTML table        jQuery(this).empty();        // Mark it as jqGrid        jQuery(this).addClass("scroll");        jQuery(this).jqGrid(jQuery.extend({            datatype: "local",            width: w,            colNames: colNames,            colModel: colModel,            multiselect: selectMultiple            //inputName: inputName,            //inputValueCol: imputName != null ? "__selection__" : null        }, options || {}));        // Add data        var a;        for (a = 0; a < data.length; a++) {            var id = null;            if (rowIds.length > 0) {                id = rowIds[a];                if (id && id.replace) {                    // We have to do this since the value of a checkbox                    // or radio button can be anything                     id = encodeURIComponent(id).replace(/[.\-%]/g, "_");                }            }            if (id === null) {                id = a + 1;            }            jQuery(this).jqGrid("addRowData", id, data[a]);        }        // Set the selection        for (a = 0; a < rowChecked.length; a++) {            jQuery(this).jqGrid("setSelection", rowChecked[a]);        }    });};