• jQuery.FlexiGrid使用总结


    经过对FlexiGrid的大量使用,及时不时琢磨下其代码,对她的脾性有了一定的了解,是该做总结的时候了。

    一、FlexiGrid下载 

    1、原版代码

    最近Paulo P. Marinas对FlexiGrid做了修改,以适应jQuery 1.4.2。看了下作者列出来的特性表,该表很长,但与过去比,却没有增加什么新功能,所以版本号不做修改,仍然是1.0b3。
    其中提到的一点值得注意,就是flexAddData方法已改写,性能是否有很大提高,还没测试,要看结果。(最近,抽时间看了一下渲染表格数据的代码,估计效率还是不理想)。还有Editable功能的增加,仍然处于长期计划中,这一点比较令人纠结。


    在此说明一下,本文仍然只是对旧版进行总结。

    下载:http://code.google.com/p/flexigrid/downloads/list 

    2、功能优化扩展版
    该版本为xuanye(http://www.cnblogs.com/xuanye )的修改版,很好,很强大。

    下载1:http://code.google.com/p/xjplugin/downloads/list

    下载2:http://xjplugin.googlecode.com/svn/trunk/ControlsSample/Javascripts/Plugins/jquery.flexigrid.js

    下载2中的代码新增了getSelectedRows()方法,获取表格行数据将更加简单。


    二、配置参数(options)说明

    默认参数设置代码:

    Js代码  收藏代码
    1. // apply default properties  
    2. p = $.extend({  
    3.     height: 200,  
    4.     //default height  
    5.      'auto',  
    6.     //auto width  
    7.     striped: true,  
    8.     //apply odd even stripes  
    9.     novstripe: false,  
    10.     min 30,  
    11.     //min width of columns  
    12.     minheight: 80,  
    13.     //min height of columns  
    14.     resizable: true,  
    15.     //resizable table  
    16.     url: false,  
    17.     //ajax url  
    18.     method: 'POST',  
    19.     // data sending method  
    20.     dataType: 'xml',  
    21.     // type of data loaded  
    22.     errormsg: 'Connection Error',  
    23.     usepager: false,  
    24.     //  
    25.     nowrap: true,  
    26.     //  
    27.     page: 1,  
    28.     //current page  
    29.     total: 1,  
    30.     //total pages  
    31.     useRp: true,  
    32.     //use the results per page select box  
    33.     rp: 15,  
    34.     // results per page  
    35.     rpOptions: [10, 15, 20, 25, 40],  
    36.     title: false,  
    37.     pagestat: 'Displaying {from} to {to} of {total} items',  
    38.     procmsg: 'Processing, please wait ...',  
    39.     query: '',  
    40.     qtype: '',  
    41.     nomsg: 'No items',  
    42.     minColToggle: 1,  
    43.     //minimum allowed column to be hidden  
    44.     showToggleBtn: true,  
    45.     //show or hide column toggle popup  
    46.     hideOnSubmit: true,  
    47.     autoload: true,  
    48.     blockOpacity: 0.5,  
    49.     onToggleCol: false,  
    50.     onChangeSort: false,  
    51.     onSuccess: false,  
    52.     onSubmit: false  
    53.     // using a custom populate function  
    54.   
    55. },  
    56. p);  

     

    参数说明:
    height: 200, //flexigrid插件的高度,单位为px
    'auto', //宽度值,auto表示根据每列的宽度自动计算
    striped: true, //是否显示斑纹效果,默认是奇偶交互的形式
    novstripe: false, //没用过,不知怎么用,还需分析源代码
    min 30, //列的最小宽度
    minheight: 80, //列的最小高度
    resizable: true, //是否可伸缩
    url: false, //ajax方式对应的url地址
    method: 'POST', // 数据发送方式
    dataType: 'xml', // 数据加载的类型
    errormsg: 'Connection Error',//错误提示信息
    usepager: false, //是否分页
    nowrap: true, //是否不换行
    page: 1, //默认当前页
    total: 1, //总页面数
    useRp: true, //是否可以动态设置每页显示的结果数
    rp: 15, // 每页默认的结果数
    rpOptions: [10,15,20,25,40],//可选择设定的每页结果数
    title: false, //标题设置
    pagestat: 'Displaying {from} to {to} of {total} items',//显示分页状态
    procmsg: ‘Processing, please wait …’,//正在处理的提示信息
    query: '',//搜索查询的条件,提交到服务器
    qtype: '',//搜索查询的类别,提交到服务器
    nomsg: 'No items',//无结果的提示信息
    minColToggle: 1, //是否允许隐藏列
    showToggleBtn: true, //显示或隐藏数据表格
    hideOnSubmit: true,//隐藏提交
    autoload: true,//自动加载
    blockOpacity: 0.5,//透明度设置
    onToggleCol: false,//当在行之间转换时
    onChangeSort: false,//当改变排序时
    onSuccess: false,//成功后执行
    onSubmit: false // 触发自定义populate的提交事件

     


    三、使用步骤说明 

    1、在<head>标识里加入引用文件代码(注意文件存放路径):

    Html代码  收藏代码
    1. link rel = "stylesheet"href = "flexigrid/flexigrid.css"type = "text/css" </link>   
    2.    <script type="text/javascript " src="jquery / jquery.1.3.2.mini.js "></script>   
    3.    <script type="text / javascript " src="flexigrid / flexigrid.js "></script>"   

        
       添加工具按钮图标样式:

    Html代码  收藏代码
    1. style type = "text/css" >   
    2. /* === 增加工具按钮图标样式  ====*/  
    3. .flexigrid div.fbutton.add  
    4.  {  
    5.     padding - left: 20px;  
    6.     background: url(images / row_add.gif) no - repeat center left;  
    7.   
    8. }  
    9.   
    10. .flexigrid div.fbutton.edit  
    11.  {  
    12.     padding - left: 20px;  
    13.     background: url(images / row_edit.gif) no - repeat center left;  
    14.   
    15. }  
    16.   
    17. .flexigrid div.fbutton.delete  
    18.  {  
    19.     padding - left: 20px;  
    20.     background: url(images / row_delete.gif) no - repeat center left;  
    21.   
    22. }  
    23.   
    24. .flexigrid div.fbutton.reset  
    25.  {  
    26.     padding - left: 20px;  
    27.     background: url(images / user_reset.gif) no - repeat center left;  
    28.   
    29. }  
    30.   
    31. .flexigrid div.fbutton.excel  
    32.  {  
    33.     padding - left: 20px;  
    34.     background: url(images / excel.gif) no - repeat center left;  
    35.   
    36. }  
    37.  < /style>/  

        为了方便以后使用,上面这段样式可以加入到flexigrid.css文件中。

    2、在<body>标识里加入代码:

    Html代码  收藏代码
    1. <table id="grid" style="display:none"></table>   

        如果要增加/编辑数据,还要加入下面这样的HTML代码:

    Html代码  收藏代码
    1.  <div id="dialog_div" style='display:none'>  
    2.    <form id="dialog_form" name="dialog_form" action="">  
    3.      <table width="100%" class="tableinput">  
    4.       <tr>  
    5.         <td width="30%">操作工号:</td>  
    6.         <td width="70%">  
    7.           <input name="username" type="text" id="username" />*八位数字  
    8.           <input name="user_id" type="hidden" id="user_id" />  
    9.         </td>  
    10.       </tr>  
    11.       <tr>  
    12.         <td>真实姓名:</td>  
    13.         <td><input name="name" type="text" id="name" /></td>  
    14.       </tr>  
    15.       <tr>  
    16.         <td>市县机构:</td>  
    17.         <td>{{$input.html_sxjg}}</td>  
    18.       </tr>  
    19.       <tr>  
    20.         <td>营业机构:</td>  
    21.         <td>{{$input.html_yyjg}}</td>  
    22.       </tr>  
    23.       <tr>  
    24.         <td>分配角色:</td>  
    25.         <td>{{$input.html_auth}}</td>  
    26.       </tr>  
    27.     </table>  
    28.    </form>  
    29. </div>  

     

    3、在<head>标识里编写JavaScript代码

    代码示例:

    Js代码  收藏代码
    1. < script type = "text/javascript" >   
    2. $(function() {  
    3.   
    4.     // 表单中的文本输入栏绑定 inputtxt 样式类  
    5.     $('#dialog_form input:text').addClass('inputtxt');  
    6.   
    7.     $("#grid").flexigrid({  
    8.         url: '{{url controller='Ghgl ' action='GetPagerData '}}',  
    9.         //url:'index.php?ctl=User&act=GetJsonData',  
    10.         dataType: 'json',  
    11.         colModel:   
    12.         [  
    13.         {  
    14.             display: '序号',  
    15.             name: 'seq',  
    16.              40,  
    17.             sortable: false,  
    18.             align: 'center'  
    19.         },  
    20.         {  
    21.             display: '#ID',  
    22.             name: 'user_id',  
    23.              40,  
    24.             sortable: true,  
    25.             align: 'left',  
    26.             hide: true  
    27.         },  
    28.         {  
    29.             display: '操作工号',  
    30.             name: 'username',  
    31.              70,  
    32.             sortable: true,  
    33.             align: 'left'  
    34.         },  
    35.         {  
    36.             display: '真实姓名',  
    37.             name: 'name',  
    38.              60,  
    39.             sortable: false,  
    40.             align: 'left'  
    41.         },  
    42.         {  
    43.             display: '分配角色',  
    44.             name: 'role',  
    45.              80,  
    46.             sortable: false,  
    47.             align: 'left'  
    48.         },  
    49.         {  
    50.             display: '市县单位',  
    51.             name: 'sxmc',  
    52.              120,  
    53.             sortable: false,  
    54.             align: 'left'  
    55.         },  
    56.         {  
    57.             display: '营业机构',  
    58.             name: 'jgmc',  
    59.              120,  
    60.             sortable: true,  
    61.             align: 'left'  
    62.         },  
    63.         {  
    64.             display: '工号创建时间',  
    65.             name: 'created',  
    66.              110,  
    67.             sortable: false,  
    68.             align: 'left',  
    69.             hide: false  
    70.         },  
    71.         {  
    72.             display: '密码更新时间',  
    73.             name: 'pwdupdated',  
    74.              110,  
    75.             sortable: false,  
    76.             align: 'left',  
    77.             hide: false  
    78.         }  
    79.         ],  
    80.         searchitems:   
    81.         [  
    82.         {  
    83.             display: '用户工号',  
    84.             name: 'username'  
    85.         },  
    86.         {  
    87.             display: '用户姓名',  
    88.             name: 'name',  
    89.             isdefault: true  
    90.         },  
    91.         {  
    92.             display: '市县单位',  
    93.             name: 'sxmc'  
    94.         },  
    95.         {  
    96.             display: '营业机构',  
    97.             name: 'jgmc'  
    98.         }  
    99.         ],  
    100.         sortname: "sx_id, jg_id, username",  
    101.         sortorder: "DESC",  
    102.         title: '<font color="#336699">操作工号维护</font>',  
    103.         usepager: true,  
    104.         useRp: true,  
    105.         rp: 15,  
    106.         showTableToggleBtn: false,  
    107.          600,  
    108.         height: 400,  
    109.         striped: true,  
    110.            
    111.         //onSubmit: addFormData,  
    112.         pagestat: '当前显示记录 {from} 到 {to} 条,总 {total} 条',  
    113.         procmsg: '正在处理,请稍等 ...',  
    114.         nomsg: '找不到符合条件的资料!',  
    115.         errormsg: '连接后台失败!',  
    116.         buttons:   
    117.         [  
    118.         {  
    119.             name: '添加',  
    120.             bclass: 'add',  
    121.             onpress: opt  
    122.         },  
    123.         {  
    124.             name: '修改',  
    125.             bclass: 'edit',  
    126.             onpress: opt  
    127.         },  
    128.         {  
    129.             name: '删除',  
    130.             bclass: 'delete',  
    131.             onpress: opt  
    132.         },  
    133.         {  
    134.             separator: true  
    135.         },  
    136.         {  
    137.             name: '导出EXCEL',  
    138.             bclass: 'excel',  
    139.             onpress: opt  
    140.         }  
    141.         ]  
    142.   
    143.     });  
    144.   
    145.     /** 
    146.      * 添加/修改对话框 
    147.      */  
    148.     $('#dialog_div').dialog({  
    149.         hide: '',  
    150.         //点击取消后隐藏,如果设为true,则无法关闭弹窗。   
    151.         autoOpen: false,  
    152.          340,  
    153.         //height:230,   
    154.         modal: true,  
    155.         //蒙层   
    156.         //title:'单位资料添加/修改',   
    157.         overlay: {  
    158.             opacity: 0.5,  
    159.             background: "black"  
    160.   
    161.         },  
    162.         buttons: {  
    163.             '关闭': function() {  
    164.                 $(this).dialog("close");  
    165.             },  
    166.             '重置': function() {  
    167.                 $(this).children('form')[0].reset();  
    168.             },  
    169.             '提交': function() {  
    170.                 addUpdate();  
    171.             }  
    172.   
    173.         }  
    174.   
    175.     });  
    176.   
    177.     /** 
    178.      * 点击工具条按钮操作 
    179.      */  
    180.     function opt(com, grid) {  
    181.         switch (com) {  
    182.             case '添加':  
    183.             $('.ui-dialog-title').html('<font color="#336699">添加操作工号</font>');  
    184.             $('#dialog_form input[name=user_id]')[0].value = '';  
    185.             $('#dialog_div').dialog('open').children('form')[0].reset();  
    186.             break;  
    187.             case '修改':  
    188.             $('.ui-dialog-title').html('<font color="#336699">修改操作工号</font>');  
    189.             selected_count = $('.trSelected', grid).length;  
    190.             if (selected_count == 0) {  
    191.                 JAlert('请选择一条记录。', '消息提示');  
    192.                 return false;  
    193.   
    194.             }  
    195.             if (selected_count > 1) {  
    196.                 jAlert('抱歉每次只能修改一条记录。', '消息提示');  
    197.                 return false;  
    198.   
    199.             }  
    200.   
    201.             // 读取表格所选行数据  
    202.             var data = new Array();  
    203.             $('.trSelected td', grid).each(function(i) {  
    204.                 data[i] = $(this).children('div').text();  
    205.   
    206.             });  
    207.             //alert(data);  
    208.   
    209. // 初始化编辑数据界面数据  
    210.             $('#dialog_form input[name=user_id]')[0].value = data[1];  
    211.             $('#dialog_form input[name=username]')[0].value = data[2];  
    212.             $('#dialog_form input[name=name]')[0].value = data[3];  
    213.             $.ajax({  
    214.                 url: '{{url controller='Ghgl ' action='GetUpdData '}}',  
    215.                 data: {  
    216.                     user_id: data[1]  
    217.                 },  
    218.                 type: 'POST',  
    219.                 dataType: 'json',  
    220.                 success: function(data) {  
    221.                     //alert($('#jg_id').options);  
    222.                     var jg_slt = $('#dialog_form #jg_id option');  
    223.                     var jg_len = jg_slt.length;  
    224.                     if (jg_len > 0) {  
    225.                         setSelected(jg_slt, data.jg_id);  
    226.   
    227.                     }  
    228.   
    229.                     var auth_radio = $('#dialog_form input:radio');  
    230.                     //alert(auth_radio.length);  
    231.                     if (auth_radio.length > 0) {  
    232.                         setChecked(auth_radio, data.auth);  
    233.   
    234.                     }  
    235.   
    236.                 }  
    237.   
    238.             });  
    239.             $('#dialog_div').dialog('open');  
    240.             break;  
    241.             case '删除':  
    242.             selected_count = $('.trSelected', grid).length;  
    243.             if (selected_count == 0) {  
    244.                 jAlert('请选择一条记录。', '消息提示');  
    245.                 return false;  
    246.   
    247.             }  
    248.             if (selected_count > 1) {  
    249.                 jAlert('抱歉每次只能删除一条记录。', '消息提示');  
    250.                 return false;  
    251.   
    252.             }  
    253.             var names = '';  
    254.             $('.trSelected td:nth-child(4) div', grid).each(function(i) {  
    255.                 if (i) {  
    256.                     names += ',';  
    257.   
    258.                 }  
    259.                 names += $(this).text();  
    260.   
    261.             });  
    262.             var ids = '';  
    263.             $('.trSelected td:nth-child(2) div', grid).each(function(i) {  
    264.                 if (i) {  
    265.                     ids += ',';  
    266.   
    267.                 }  
    268.                 ids += $(this).text();  
    269.   
    270.             })  
    271.             /* 
    272.                 if (ids == '') { 
    273.                     alert('请选择删除记录,允许同时选择多条记录。'); 
    274.                     return; 
    275.                 }*/  
    276.             /* 
    277.                 if(confirm("确认删除[" + names + "]的用户工号吗?")){  
    278.                     del(ids);  
    279.                 }*/  
    280.             jConfirm("确认删除[<font color='#FF0000'>" + names + "</font>]的用户工号吗?", '删除确认',   
    281.             function(btn) {  
    282.                 if (btn) {  
    283.                     del(ids);  
    284.                 }  
    285.   
    286.             });  
    287.             break;  
    288.             case '导出EXCEL':  
    289.             document.location.href = "{{url controller='Ghgl' action='Export'}}";  
    290.             break;  
    291.   
    292.         }  
    293.   
    294.     }  
    295.   
    296.     /** 
    297.      * 添加记录 
    298.      */  
    299.     function addUpdate() {  
    300.         $('#dialog_form').ajaxSubmit({  
    301.             //$('#dialog_form').ajaxform({  
    302.             url: "{{url controller='Ghgl' action='Save'}}",  
    303.             type: 'POST',  
    304.             dataType: 'json',  
    305.             resetForm: true,  
    306.             success: function(data) {  
    307.                 if (data.success) {  
    308.                     $('#grid').flexReload();  
    309.                     $('#dialog_div').dialog('close');  
    310.   
    311.                 } else {  
    312.                     jAlert(data.msg, '消息提示');  
    313.                     return false;  
    314.   
    315.                 }  
    316.   
    317.             },  
    318.             error: function() {}  
    319.   
    320.         });  
    321.   
    322.     };  
    323.   
    324.     /** 
    325.      * 删除记录 
    326.      */  
    327.     function del(ids) {  
    328.         $.ajax({  
    329.             url: "{{url controller='Ghgl' action='Del'}}",  
    330.             data: {  
    331.                 ids: ids  
    332.             },  
    333.             type: 'POST',  
    334.             dataType: 'json',  
    335.             success: function(data) {  
    336.                 if (data.success) {  
    337.                     $('#grid').flexReload();  
    338.   
    339.                 } else {  
    340.                     jAlert(data.msg, '消息提示');  
    341.                     return false;  
    342.   
    343.                 }  
    344.   
    345.             }  
    346.   
    347.         });  
    348.   
    349.     };  
    350.   
    351.     /** 
    352.      * 重置密码 
    353.      */  
    354.     function reset(id) {  
    355.         $.ajax({  
    356.             url: "{{url controller='Ghgl' action='Reset'}}",  
    357.             data: {  
    358.                 user_id: id  
    359.             },  
    360.             type: 'POST',  
    361.             dataType: 'json',  
    362.             success: function(data) {  
    363.                 if (data.success) {  
    364.                     jAlert(data.msg, '消息提示');  
    365.                     return;  
    366.   
    367.                 } else {  
    368.                     jAlert(data.msg, '错误提示');  
    369.                     return false;  
    370.   
    371.                 }  
    372.   
    373.             },  
    374.             error: function() {}  
    375.   
    376.         });  
    377.   
    378.     };  
    379.   
    380.     // 根据 value 初始化下拉列表框  
    381.     function setSelected(slt, value) {  
    382.         for (var i = 0; i < slt.length; i++) {  
    383.             if (slt[i].value == value) {  
    384.                 slt[i].selected = true;  
    385.   
    386.             } else {  
    387.                 slt[i].selected = false;  
    388.   
    389.             }  
    390.   
    391.         }  
    392.   
    393.     };  
    394.   
    395.     // 根据 value 初始化单选按钮  
    396.     function setChecked(slt, value) {  
    397.         for (var i = 0; i < slt.length; i++) {  
    398.             if (slt[i].value == value) {  
    399.                 slt[i].checked = true;  
    400.   
    401.             } else {  
    402.                 slt[i].checked = false;  
    403.   
    404.             }  
    405.   
    406.         }  
    407.   
    408.     };  
    409.   
    410. });  
    411.  < /script>/  

    其中代码段:

    Js代码  收藏代码
    1. // 读取表格所选行数据  
    2. var data = new Array();  
    3. $('.trSelected td', grid).each(function(i) {  
    4.   data[i] = $(this).children('div').text();  
    5. });  
    6. //alert(data);  

     为读取表格所选行数据,通过$('.trSelected td', grid)来读取。

    Js代码  收藏代码
    1. var ids = '';    
    2. $('.trSelected td:nth-child(2) div',grid).each(function(i){    
    3.   if(i){  
    4.         ids += ',';  
    5.   }  
    6.       ids += $(this).text();    
    7. })  

     为读取所选行单元格数据代码,通过:$('.trSelected td:nth-child(2) div',grid)来读取,如果允许多选,读取回来的是一个数组值。注意:td:nth-child(2)的意思为所选行的第二个单元格,因为:nth-child(index)的索引值从1起。

    FlexiGrid.options参数介绍:

    1、colModel:列定义数组,用来设置数据网格的表头及数据显示格式。

    参数说明:
    display:设置列表头名称,必须设置,类型:string,默认值:无。
    name:字段名称,必须设置,类型:string,默认值: 无。注意:如果dataType参数设置为json(dataType: 'json'),则name值必须与返回的元素名对应。
    width:设置列宽度,必须设置,类型:数值(单位为像素px),默认值:无。
    sortable:是否可排序,类型:boolen,默认值:false,不排序。
    process:处理程序,类型:
    function,可格式化单元格。
    hide:设置列是否隐藏,类型:boolen,默认值:false
    align:设置列数据对齐方式,有三个参数:left、center、right。


        代码示例:

    Js代码  收藏代码
    1. colModel:   
    2. [  
    3. {  
    4.     display: '序号',  
    5.     name: 'seq',  
    6.      40,  
    7.     sortable: false,  
    8.     align: 'center'  
    9. },  
    10. {  
    11.     display: '#ID',  
    12.     name: 'user_id',  
    13.      40,  
    14.     sortable: true,  
    15.     align: 'left',  
    16.     hide: true  
    17. },  
    18. {  
    19.     display: '操作工号',  
    20.     name: 'username',  
    21.      70,  
    22.     sortable: true,  
    23.     align: 'left'  
    24. },  
    25. {  
    26.     display: '真实姓名',  
    27.     name: 'name',  
    28.      60,  
    29.     sortable: false,  
    30.     align: 'left'  
    31. },  
    32. {  
    33.     display: '分配角色',  
    34.     name: 'role',  
    35.      80,  
    36.     sortable: false,  
    37.     align: 'left'  
    38. },  
    39. {  
    40.     display: '市县单位',  
    41.     name: 'sxmc',  
    42.      120,  
    43.     sortable: false,  
    44.     align: 'left'  
    45. },  
    46. {  
    47.     display: '营业机构',  
    48.     name: 'jgmc',  
    49.      120,  
    50.     sortable: true,  
    51.     align: 'left'  
    52. },  
    53. {  
    54.     display: '工号创建时间',  
    55.     name: 'created',  
    56.      110,  
    57.     sortable: false,  
    58.     align: 'left',  
    59.     hide: false  
    60. },  
    61. {  
    62.     display: '密码更新时间',  
    63.     name: 'pwdupdated',  
    64.      110,  
    65.     sortable: false,  
    66.     align: 'left',  
    67.     hide: false  
    68. }  
    69. ],  


    2、buttons:工具栏Button定义数组,用来设置数据网格的工具条按钮。

    参数说明:
    name:Botton的标识,类型:string, 默认值:无
    bclass :样式, 类型:boolen,默认值:无
    onpress :当button被点击时触发的事件接受button的name为第一个参数,Grid为第二个参数的一个function
    separator :是否显示分隔符

        代码示例:

    Js代码  收藏代码
    1. buttons:   
    2. [  
    3. {  
    4.     name: '添加',  
    5.     bclass: 'add',  
    6.     onpress: opt  
    7. },  
    8. {  
    9.     name: '修改',  
    10.     bclass: 'edit',  
    11.     onpress: opt  
    12. },  
    13. {  
    14.     name: '删除',  
    15.     bclass: 'delete',  
    16.     onpress: opt  
    17. },  
    18. {  
    19.     separator: true  
    20. },  
    21. {  
    22.     name: '导出EXCEL',  
    23.     bclass: 'excel',  
    24.     onpress: opt  
    25. }  
    26. ]  


        其中:
        
        name:设置按钮文字
        separator:设置是否显示分隔线
        bclass:设置按钮样式,示例:

    Html代码  收藏代码
    1. style >   
    2. .flexigrid div.fbutton.add  
    3.  {  
    4.     background: url(.. / lib / jquery / flexigrid / css / images / row_add.gif) no - repeat center left;  
    5.   
    6. }  
    7.   
    8. .flexigrid div.fbutton.edit  
    9.  {  
    10.     background: url(.. / lib / jquery / flexigrid / css / images / row_edit.gif) no - repeat center left;  
    11.   
    12. }  
    13.   
    14. .flexigrid div.fbutton.delete  
    15.  {  
    16.     background: url(.. / lib / jquery / flexigrid / css / images / row_delete.gif) no - repeat center left;  
    17.   
    18. }  
    19.   
    20. .flexigrid div.fbutton.reset  
    21.  {  
    22.     background: url(.. / images / user_reset.gif) no - repeat center left;  
    23.   
    24. }  
    25.   
    26. .flexigrid div.fbutton.excel  
    27.  {  
    28.     background: url(.. / images / excel.gif) no - repeat center left;  
    29.   
    30. }  
    31.  < /style>  

        onpress:点击按钮时触发的事件,接受button的name为第一个参数,grid为第二个参数的一个function。

        示例代码:

    Js代码  收藏代码
    1. /** 
    2.      * 点击工具条按钮操作 
    3.      */  
    4. function opt(com, grid) {  
    5.     switch (com) {  
    6.         case '添加':  
    7.         ...  
    8.         break;  
    9.         case '修改':  
    10.         ...  
    11.         break;  
    12.         case '删除':  
    13.         ...  
    14.         break;  
    15.         case '导出EXCEL':  
    16.         ...  
    17.         break;  
    18.   
    19.     }  
    20.   
    21. }  

     


    3、后台PHP代码(json):

    摘自FlexiGrid最新版的示例代码:

    Php代码  收藏代码
    1. function runSQL($rsql) {  
    2.   
    3.     $connect = mysql_connect($hostname,$username,$password) or die ("Error: could not connect to database");  
    4.     $db = mysql_select_db($dbname);  
    5.   
    6.     $result = mysql_query($rsql) or die ('test');  
    7.     return $result;  
    8.     mysql_close($connect);  
    9. }  
    10.   
    11. function countRec($fname,$tname) {  
    12.     $sql = "SELECT count($fname) FROM $tname ";  
    13.     $result = runSQL($sql);  
    14.     while ($row = mysql_fetch_array($result)) {  
    15.     return $row[0];  
    16.     }  
    17. }  
    18.   
    19. $page = $_POST['page'];  
    20. $rp = $_POST['rp'];  
    21. $sortname = $_POST['sortname'];  
    22. $sortorder = $_POST['sortorder'];  
    23.   
    24. if (!$sortname) $sortname = 'name';  
    25. if (!$sortorder) $sortorder = 'desc';  
    26.   
    27. $sort = "ORDER BY $sortname $sortorder";  
    28.   
    29. if (!$page) $page = 1;  
    30. if (!$rp) $rp = 10;  
    31.   
    32. $start = (($page-1) * $rp);  
    33.   
    34. $limit = "LIMIT $start, $rp";  
    35.   
    36. $sql = "SELECT iso,name,printable_name,iso3,numcode FROM country $sort $limit";  
    37. $result = runSQL($sql);  
    38.   
    39. $total = countRec('iso','country');  
    40.   
    41. // 生成json格式数据  
    42. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );  
    43. header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );  
    44. header("Cache-Control: no-cache, must-revalidate" );  
    45. header("Pragma: no-cache" );  
    46. header("Content-type: text/x-json");  
    47. $json = "";  
    48. $json .= "{ ";  
    49. $json .= "page: $page, ";  
    50. $json .= "total: $total, ";  
    51. $json .= "rows: [";  
    52. $rc = false;  
    53. while ($row = mysql_fetch_array($result)) {  
    54.     if ($rc) $json .= ",";  
    55.     $json .= " {";  
    56.     $json .= "id:'".$row['iso']."',";  
    57.     $json .= "cell:['".$row['iso']."'";  
    58.     $json .= ",'".addslashes($row['name'])."'";  
    59.     $json .= ",'".addslashes($row['printable_name'])."'";  
    60.     $json .= ",'".addslashes($row['iso3'])."'";  
    61.     $json .= ",'".addslashes($row['numcode'])."']";  
    62.     $json .= "}";  
    63.     $rc = true;  
    64. }  
    65. $json .= "] ";  
    66. $json .= "}";  
    67. echo $json;  

    本人的后台后代码:

    Php代码  收藏代码
    1. /** 
    2.      * 返回JSON分页数据到前台 
    3.      * 
    4.      */  
    5.     function actionGetPagerData()  
    6.     {  
    7.         $user = $this->user;  
    8.   
    9.         $page = ($_POST['page']) ? $_POST['page'] : 1;  
    10.         $limit = ($_POST['rp'])?$_POST['rp'] : 15;  
    11.         $sortname = ($_POST['sortname']) ? $_POST['sortname'] : 'username';  
    12.         $sortorder = ($_POST['sortorder']) ? $_POST['sortorder'] : 'DESC';  
    13.   
    14.         $sort = "$sortname $sortorder";  
    15.         $offset = ($page - 1) * $limit;  
    16.   
    17.         $query = ($_POST['query']) ? trim($_POST['query']) : '';  
    18.         $qtype = ($_POST['qtype']) ? trim($_POST['qtype']) : '';  
    19.         if ($qtype == 'name' || $qtype == 'sxmc') {  
    20.             $query = mb_convert_encoding($query, 'GB2312', 'utf-8');  
    21.         }  
    22.   
    23.         if ($user['RBAC_ROLES'][0] == 'SYSTEM_ADMIN') {  
    24.             $conditions = array(  
    25.                 array('auth', 1, '=', 'OR'),  
    26.                 array('auth', 2, '='),  
    27.             );  
    28.         } elseif ($user['RBAC_ROLES'][0] == 'POWER_USER') {  
    29.             $conditions = array(  
    30.                 array('sx_id', $user['SXID'], '=', 'AND'),  
    31.                 array('auth', 3, '=', 'OR'),  
    32.                 array('sx_id', $user['SXID'], '=', 'AND'),  
    33.                 array('auth', 4, '='),  
    34.             );  
    35.         }  
    36.   
    37.         if ($query  && $user['RBAC_ROLES'][0] == 'POWER_USER') {  
    38.             $conditions = array(  
    39.                 array('sx_id', $user['SXID'], '=', 'AND'),  
    40.                 array($qtype, $query, '=')  
    41.             );  
    42.         }  
    43.         if ($qtype == 'name' && $query != ''  && $user['RBAC_ROLES'][0] == 'POWER_USER') {  
    44.             $conditions = array(  
    45.                 array('sx_id', $user['SXID'], '=', 'AND'),  
    46.                 array($qtype, '%' . $query . '%', 'LIKE')  
    47.             );  
    48.         }  
    49.         if ($qtype == 'sxmc' && $query != '' && $user['RBAC_ROLES'][0] == 'SYSTEM_ADMIN') {  
    50.             $cxtj = array(  
    51.                 array('sxmc', '%' . $query . '%', 'LIKE')  
    52.             );  
    53.             $sxjg = & FLEA::getSingleton('Table_Sxjg');  
    54.             $row = $sxjg->find($cxtj);  
    55.   
    56.             $conditions = array(  
    57.                 array('sx_id', $row['SXID'], '=', 'AND'),  
    58.                 array('auth', 1, '=', 'OR'),  
    59.                 array('sx_id', $row['SXID'], '=', 'AND'),  
    60.                 array('auth', 2, '='),  
    61.             );  
    62.         }  
    63.         if ($qtype == 'jgmc' && $query != '' && $user['RBAC_ROLES'][0] == 'POWER_USER') {  
    64.             $cxtj = array(  
    65.                 array('sx_id', $this->user['SXID'], '=', 'AND'),  
    66.                 array('jgmc', '%' . $query . '%', 'LIKE')  
    67.             );  
    68.             $tblYyjg = & FLEA::getSingleton('Table_Yyjg');  
    69.             $row = $tblYyjg->find($cxtj);  
    70.             $conditions = array(  
    71.                 array('sx_id', $this->user['SXID'], '=', 'AND'),  
    72.                 array('jg_id', $row['jg_id'], '=')  
    73.             );  
    74.         }  
    75.   
    76.         //$conditions = null;  
    77.         $this->_tblUsers->enableLinks();  
    78.         $rows = $this->_tblUsers->findAll($conditions, $sort, array($limit, $offset));  
    79.         $rs = $this->_tblUsers->findAll($conditions);  
    80.         $total = count($rs);  
    81.         $json = "";  
    82.         $json .= "{ ";  
    83.         $json .= "page: $page, ";  
    84.         $json .= "total: $total, ";  
    85.         $json .= "rows: [";  
    86.         $rc = false;  
    87.         $i = 1;  
    88.         foreach ($rows as $row) {  
    89.             if ($rc) $json .= ",";  
    90.             $json .= " {";  
    91.             $json .= "user_id:'".$row['user_id']."',";  
    92.             $json .= "cell:['".$i."'";  
    93.             $json .= ",'".$row['user_id']."'";  
    94.             $json .= ",'".$row['username']."'";  
    95.             $json .= ",'".$row['name']."'";  
    96.             $json .= ",'".$row['roles'][0]['rolename_cn']."'";  
    97.             $json .= ",'".$row['sxjg']['sxmc']."'";  
    98.             $json .= ",'".addslashes($row['yyjg']['jgmc'])."'";  
    99.             $json .= ",'".$row['created']."'";  
    100.             //$json .= ",'".$row['updated']."']";  
    101.             $json .= ",'".$row['pwdupdated']."']";  
    102.             $json .= "}";  
    103.             $rc = true;  
    104.             $i++;  
    105.         }  
    106.         $json .= "] ";  
    107.         $json .= "}";  
    108.         echo $json;  
    109.         exit;  
    110.     }  


    四、功能优化扩展版说明 

    功能优化扩展版的改变:

    1、修改了仿ext的皮肤,界面更加漂亮;
    2、优化了渲染表格代码,速度提高了60%;
    3、增加了显示checkbox列功能;
    4、为方便处理行数据,增加了行数据绑定功能。

    options新增参数:

    Js代码  收藏代码
    1. qop: "Eq", //搜索的操作符  
    2. showcheckbox: false, //是否在列首添加checkbox  
    3. rowhandler: false, //在生成行时绑定事件,如双击,右键等  
    4. rowbinddata: false, // 是否在行上绑定数据  
    5. extParam: {}, // 扩展外部参数动态注册到grid,实现如自定义查询等操作  
    6. onrowchecked: false, // checkbox选中状态发生变化时触发的事件  
    7. gridClass: "bbit-grid" //绑定样式  

    buttons新增参数: 

    btnText: 设置工具按钮附加文本,原来的为displayname,我这里改成了btnText。

    示例:

    Js代码  收藏代码
    1. buttons:  
    2. [  
    3.     {name: 'Add', btnText: "新增", bclass: 'add', onpress: function(Add, grid){alert('这是新增操作。');return false;}},  
    4.     {name: 'Edit', btnText: "修改", bclass: 'edit', onpress: ''},  
    5.     {name: 'Delete', btnText: "删除", bclass: 'delete', onpress: ''},  
    6.     {separator: true},  
    7.     {name: 'Export', btnText: "导出Excel", bclass: 'excel', onpress: ''}  
    8. ]  

    新增方法1:

    Js代码  收藏代码
    1. var ids = $("#grid").getCheckedRows(); 可以获取到选中行的主键值,里面保存的是记录的ID数组。  

    *注意:

    该方法需要十分注意JSON分页格式数据,举例说明:

    Js代码  收藏代码
    1. ...  
    2. $json .= " {";    
    3. $json .= "user_id:'".$row['user_id']."',";    
    4. $json .= "cell:['".$i."'";    
    5. $json .= ",'".$row['user_id']."'";  
    6. ...  

     

    其中的:

    Js代码  收藏代码
    1. $json .= "user_id:'".$row['user_id']."',";    

     

    里面的主键名必须统一使用id,即为:

    Js代码  收藏代码
    1. $json .= "id:'".$row['user_id']."',";    

     getCheckedRows()才能正确获取数据。

    新增方法2:

    Java代码  收藏代码
    1. var rows = $("#grid).getSelectedRows(); // 获取表格行数据  

     
    *注意,该方法需要将 rowbinddata 参数设为 true,而且返回的数据为二维数组。

    同时,为了保证该方法在IE、FF下都能使用正常,需要修改FlexiGrid.js代码。

    打开FlexiGrid.js文件,找到代码行:

     

    Js代码  收藏代码
    1. items.push($(this).attr("ch").split('_FG$SP_'));  

     

    将其修改为:

    Js代码  收藏代码
    1. items.push($(this).attr("CH").split('_FG$SP_'));  

     


    功能实现示例: 

    1、查询的布局可自行设置,完了调用方法刷新grid即可,类似如下所示:

    Js代码  收藏代码
    1. var p = { extParam: [  
    2.     { name: "stuName", value: $("#selectinput").val() },  
    3.     { name: "stuId", value: $("#selectStuId").val() },  
    4.     { name: "stuNo", value: $("#selectNo").val() },  
    5.     { name: "stuGrade", value: $("#selectGrade").val() },  
    6.     { name: "SID", value: $("#sugvalue").val() },  
    7.     { name: "Sname", value: $("#sugname").val() },  
    8.     { name: "Sgust", value: $("#suggust").val() }  
    9.     ]  
    10. };  
    11. $("#grid").flexOptions(p).flexReload();  

     

    2、grid中有一些记录是已经选中的,我怎样让它们从数据库中查出来时前面的checkbox设置成选中?

    首先把是否选中的值作为列表中的列和其他数据一起查询回来一次,
    然后再在Flexigrid中的 rowhandler参数定义一个函数,如下所示:

    Js代码  收藏代码
    1. rowhandler: InitGridCheck,  

     

    函数实现:

    Js代码  收藏代码
    1. function InitGridCheck(tr) {  
    2.     var ch = $.browser.msie ? tr.ch : target.getAttribute("ch");  
    3.     var cell = ch.split("_FG$SP_");  
    4.     if(cell[7] != 1){return;}  
    5.     var chkb = $(tr).find(":checkbox");  
    6.     if (chkb.length>0) {  
    7.         chkb[0].checked = true;  
    8.         chkb[0].defaultChecked = true;  
    9.         $(tr).addClass('trSelected');  
    10.     }  
    11. }  

    除错:

    由于xuanye的修改版代码在取消显示checkbox列(showcheckbox: false)时,存在无法单击表格行时无法选定记录行的bug,因为如果不能选定记录行,则无法进行编辑、删除等操作。

    打开jquery.flexigrid.js文件,找到735行,加入单击表格行事件代码:

    Js代码  收藏代码
    1. $('tbody tr', g.bDiv).each(  
    2. function() {  
    3.     // 增加单击行时的处理代码(modified by hegz 2009/03/29)  
    4.     $(this)  
    5.     .click(  
    6.     function(e)  
    7.     {  
    8.         var obj = (e.target || e.srcElement);  
    9.         if (obj.href || obj.type) return true;  
    10.         if ($(this).hasClass('trSelected')) {  
    11.             $(this).removeClass('trSelected');  
    12.             if (p.showcheckbox)  
    13.             $("input.itemchk", this)[0].checked = false;  
    14.   
    15.         } else {  
    16.             $(this).addClass('trSelected');  
    17.             if (p.showcheckbox)  
    18.             $("input.itemchk", this)[0].checked = true;  
    19.   
    20.         }  
    21.         if (p.onrowchecked) p.onrowchecked.call(this);  
    22.         if (p.singleSelect) $(this).siblings().removeClass('trSelected');  
    23.   
    24.     }  
    25.     );  
    26.     // modified end  
    27.     ...  

    其实,原版代码是有这样的代码的,但xuanye修改后取消了。

    原版FlexiGrid代码:

    Js代码  收藏代码
    1. addRowProp: function() {  
    2.     $('tbody tr', g.bDiv).each(function() {  
    3.         $(this).click(function(e) {  
    4.             var obj = (e.target || e.srcElement);  
    5.             if (obj.href || obj.type) return true;  
    6.             $(this).toggleClass('trSelected');  
    7.             if (p.singleSelect) $(this).siblings().removeClass('trSelected')  
    8.         }).mousedown(function(e) {  
    9.             if (e.shiftKey) {  
    10.                 $(this).toggleClass('trSelected');  
    11.                 g.multisel = true;  
    12.                 this.focus();  
    13.                 $(g.gDiv).noSelect()  
    14.             }  
    15.         }).mouseup(function() {  
    16.             if (g.multisel) {  
    17.                 g.multisel = false;  
    18.                 $(g.gDiv).noSelect(false)  
    19.             }  
    20.         }).hover(function(e) {  
    21.             if (g.multisel) {  
    22.                 $(this).toggleClass('trSelected')  
    23.             }  
    24.         },  
    25.         function() {});  
    26.         if ($.browser.msie && $.browser.version < 7.0) {  
    27.             $(this).hover(function() {  
    28.                 $(this).addClass('trOver')  
    29.             },  
    30.             function() {  
    31.                 $(this).removeClass('trOver')  
    32.             })  
    33.         }  
    34.     })  
    35. },  

    (今天,通过与xuanye兄交流,这个不是bug,只是通过右键菜单来支持,现在的最新代码已支持该功能,我有可能白忙活了,哈哈。)

    五、jQuery 1.4.2支持测试

    jQuery 1.4.2推出后,由于效率比jQuery 1.3.2高很多,因此我们的项目开发需要逐渐过渡到jQuery 1.4.2,以改善项目的整体运行效率。怀着这样的目的,这两天来我抽时间对FlexiGrid在jQuery 1.4.2下的运行做了简单的测试。发现旧版本在jQuery 1.4.2也能正常运行,但由于jQuery 1.4.2对JSON数据格式有严格的限制,名值对必须加双引号括起来,否则将发生JSON数据解析错误。如下图所示:

     当然了,如果想弹出上面的警告框,需要稍微修改下Flexigrid的js代码。

    打开Flexigrid的源代码,找到populate()方法,将其中的Ajax error回调函数修改为:

    Js代码  收藏代码
    1. error:function (data, textStatus, errorThrown) {  
    2.                         alert(textStatus);  
    3.                     }  

    即可。不过,测试完后要记得将源代码恢复原状就行。

    六、结束语

    Paulo P. Marinas 的目标是致力打造功能完善、简单易用的轻量级grid。他确保将来增加新的功能后,代码经过压缩,大小不超过20K,这确实令人赞赏。但其一直以来计划增加的Editable功能始终无法实现,就令我等有点失望了,或者xuanye等大虾在不久的将来会去扩充实现这一功能也未可知。


    七、参考资料 

    1、官方网站(http://www.flexigrid.info/ )。
    2、基于jQuery的GridView-Flexigrid(2)-扩展和修复(http://www.cnblogs.com/xuanye/archive/2009/11/08/Xuanye_jQuery_FlexiGrid_Demo.html )
    3、基于jQuery的GridView-FlexiGrid的使用和改造(1)--如何使用,完全参数说明(http://www.cnblogs.com/xuanye/archive/2009/11/04/Xuanye_jQuery_FlexiGrid.html )

  • 相关阅读:
    H5前端上传文件的几个解决方案
    MyEclipse和Eclipse各个版本的汉化破解(包括7.59.0和Eclips的ehelios、indigo各版本)
    学习C#中的事件和委托
    JS学习笔记(一)JS处理JSON数据
    图解Eclipse开发C++、C语言的配置过程使用CDT和MinGw
    ASP.NET使用C#实现的最简单的验证码方法
    微信公众号支付|微信H5支付|微信扫码支付|小程序支付|APP微信支付解决方案总结
    PHP开发笔记(二)PHP的json_encode和json_decode问题
    C博客作业00——我的第一篇博客
    extern "c"
  • 原文地址:https://www.cnblogs.com/ranzige/p/3818248.html
Copyright © 2020-2023  润新知