六、jqGrid

jqGrid
  • jqGrid是一个在jQuery基础上封装的一个表格控件,以ajax的方式和服务器端通信

  • jQuery自定义函数实现表格

    //myGrid.js	初始化一个表格
    /**设计一个参数,类型是一个js对象
     *@param options的设计属性:
     * colNames:类型是一个数组
     * data:代表表格填充的数据
     * {
     *     colNames:[ 'ID','Name','Salary' ],
     *     data:[
     *         {id:1,name:'',salary:''} //代表一行数据
     *     ]
     * }
     */
    $.fn.initTable = function(option){
        //动态的创建表格中的行和列
        let $tr = $('<tr></tr>');
        //动态的创建列
        for(let i =0;i<option.colNames.length;i++){
            let $td = $('<td>'+option.colNames[i]+'</td>');
            $tr.append($td);
        }
        let $thead = $('<thead></thead>').append($tr);
        $(this).append($thead);
        //设置表格样式
        $(this).attr('width', '500px');
    }
    
    
    <body>
    <table id="tt"></table>
    <button type="button" id="btn">初始化数据表格</button>
    
    <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
    <script src="js/jquery-3.3.1.min.js"></script>
    <!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
    <script src="js/bootstrap.min.js"></script>
    <script src="js/myGrid.js"></script>
    <script>
        $(function(){
            $('#btn').click(function(){
                $('#tt').initTable({
                    colNames:['ID','Name','Salary','Age','deptName']
                });
            });
        });
    </script>
    </body>
    
  • 使用jqGrid开发

    <head>
    	........
        <link href="jqgrid/css/css/cupertino/jquery-ui-1.8.16.custom.css" rel="stylesheet">
        <link href="jqgrid/css/ui.jqgrid.css" rel="stylesheet">
    	<style>
            .tt_salary{
                background-color: silver;
                color: hotpink;
            }
        </style>
    </head>
    <body>
    <table id="tt"></table>
    
    <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
    <script src="js/jquery-3.3.1.min.js"></script>
    <!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
    <script src="jqgrid/js/i18n/grid.locale-cn.js"></script>
    <script src="jqgrid/js/jquery.jqGrid.src.js"></script>
    <script>
        $(function(){
            $('#tt').jqGrid({
                url:'emp.json',     //加载远程数据的路径
                datatype:'json',    //接收的响应数据的类型 json
                colNames:['Id','Name','Salary','Age','DeptName'],       //指定表头的名字
                colModel:[      //给每列匹配的规则
                    {name:'id'},
                    {name:'name'},
                    {
                        name:'salary',
                        align:'center',
                        classes:'tt_salary',     //给当前列指定class属性值,用于定义css样式
                        fixed:true,     //固定列宽为默认的宽度,其他地方有其余列平分
                        resizable:true      //是否运行拖拽改变列的宽度,默认为true
                    },
                    {name:'age'},
                    {name:'deptName'}
                ],
                autowidth:true      //根据父容器大小,自动计算每列的宽度
            });
        });
    </script>
    </body>
    //引入的数据emp.json
    [
      {"id": 1,"name":"Mo","salary": "30000","age": 18,"deptName": "研究生"},
      {"id": 2,"name":"Yuan","salary": "30000","age": 19,"deptName": "博士"},
      {"id": 3,"name":"Hang","salary": "30000","age": 18,"deptName": "本科"}
    ]
    
  • 后台加载数据及动态改变

    <script>
            $(function () {
                $('#tt').jqGrid({
                    url: '/emp/findAllEmp',
                    datatype: 'json',
                    colNames: ['编号','姓名','工资','年龄','部门名称'],
                    cellEdit:true,  //开启表格编辑模式
                    cellurl:'emp/editEmp',        //指定编辑后提交的路径
                    colModel:[
                        {name:'id'},
                        {
                            name:'name',
                            editable:true,   //开启列编辑模式
                            edittype:'text',    //指定编辑当前列的类型
                        },
                        {
                            name:'salary',
                            editable:true,
                            //number 只能为数字 required 此字段必须有值
                            editrules:{number:true,required:true}     //自定义,规定单元格编辑内容的类型,类似于表单验证
                        },
                        {name:'age'},
                        {
                            name:'deptName',
                            editable:true,
                            edittype: 'select',
                            //<option value="1">xxx</option>
                            //editoptions:{value:"1:本科生;2:研究生"},    加载静态数据
                            editoptions:{dataUrl:'dept.html'}        //加载远程数据,即后台数据
                        }
                    ],
                    autowidth:true,
                    multiselect:true,       //在首列前加入一列checkbox
                });
            });
    </script>
    
    <body>
    	<table id="tt"></table>
    </body>
    
    //dept.html
    <select name="" id="">
        <option value="1">本科生</option>
        <option value="2">研究生</option>
        <option value="3">博士狗</option>
    </select>
    
  • 列属性formatter自定义单元格展示的数据(员工对部门)

    public class Emp implements Serializable {
        private Integer id;
        private String name;
        private Double salary;
        private Integer age;
    
        private Dept dept;	//封装属性需要传入id,展示需要展示内容,此时需要formatter自定义
    }
    
    <script>
            $(function () {
                $('#tt').jqGrid({
                    url:'/emp/findAllEmp',
                    datatype:'json',
                    colNames:['编号','姓名','工资','年龄','部门名称'],
                    cellEdit:true,  //开启表格编辑模式
                    cellurl:'/emp/editEmp',     //指定编辑后提交的路径
                    colModel:[
                        {name:'id'},
                        {
                            name:'name',
                            editable:true,      //开启列编辑模式
                            edittype:'text',      //指定编辑当前列的类型
                        },
                        {
                            name:'salary',
                            editable:true,
                            editrules:{number:true,required:true}
                        },
                        {name:'age'},
                        {
                            name:'dept.deptName',
                            editable:true,
                            edittype:'select',
                            editoptions:{dataUrl:'dept.html'},
                            /**
                             * @param value 是当前列匹配到的远端数据
                             * @param options   当前列的操作属性对象
                             * @param row   当前行匹配到的数据对象
                             */
                            formatter:function(value,options,row){
                                console.log(value, options, row);
                                //当前函数的返回值会展示在当前列中
                                return row.dept.deptName;
                        	}
                        }
                    ],
                    autowidth:true,
                    multiselect:true
                })
            });
    </script>
    
  • 分页

    /**
         * @param page  接收当前的页码
         * @param rows  接收每页显示信息的条数
         * @return
    */
    @RequestMapping("findAllEmp")
    @ResponseBody
    public Map<String,Object> findAllEmp(Integer page,Integer rows){
            System.out.println("find all emp");
            List<Emp> emps = Arrays.asList(		//模拟数据库
                    new Emp(1, "mo", 100.0, 18,new Dept(1,"本科生")),
                    new Emp(2, "yuan", 200.0, 19,new Dept(2,"博士狗")),
                    new Emp(3, "hang", 300.0, 18,new Dept(3,"研究生")),
                    new Emp(4, "hang", 300.0, 18,new Dept(3,"研究生")),
                    new Emp(5, "hang", 300.0, 18,new Dept(3,"研究生")),
                    new Emp(6, "hang", 300.0, 18,new Dept(3,"研究生"))
            );
            /**
             * 计算总页数
             */
            Integer total = null;
            if(200%rows ==0){
                total = 200/rows;
            }else{
                total = 200/rows+1;
            }
            Map<String,Object> maps = new HashMap<>();
            maps.put("rows",emps);
            maps.put("page",page);     //当前页
            maps.put("total",total);       //总页数
            maps.put("records",rows);        //总记录数
            return maps;
    }
    
    <script>
            $(function () {
                $('#tt').jqGrid({
                    ......
                    ......
                    autowidth:true,
                    multiselect:true,
                    
                    //当用户触发上一页、下一页和更换每页显示记录数的时候,数据表格会自动向后台发送请求,同时传递两个分页的核心参数:当前页面rows和每页显示的记录数rows
                    pager:'#pg',   //指定分页的工具栏
                    rowList:[5,10,15,20,50],   //指定每页显示信息条数的列表选项,默认每页显示20条
                    rowNum:5,   //指定默认每页显示的条数,值必须是rowList中的一个
                    viewrecords:true,   //指定是否显示信息的总条数
                    page:1,     //指定默认显示第几页
    
                })
            });
    </script>
    
  • 加入编辑数据的工具栏 .navGrid;当使用不同的工具栏按钮触发的表单进行提交时,jqGrid会向后台自动发送一个oper参数,代表当前的操作,有:add添加,edit编辑,del删除

    <script>
            $(function () {
                $('#tt').jqGrid({
                    .....
                    .....
                    page:1,     //指定默认显示第几页
                    editurl:'/emp/editEmp',     //指定模态框中表单编辑后提交的路径
                    /**     navGird('',{})
                     *  第一个参数,指定初始化工具栏的div选择器
                     *  第二个参数,控制显示哪些工具栏,默认都显示
                     *  第三个参数,控制添加完毕后是够自动关闭模态框
                     */
                }).navGrid('#pg',{add:true,edit:true,del:true,search:true,refresh:true},
                    {
                        closeAfterEdit:true     //在编辑执行完毕后,自动关闭模态框
                    },
                    {
                        closeAfterAdd:true      //在添加执行完毕后,自动关闭模态框
                    });
            });
    </script>
    
    @RequestMapping("editEmp")
    @ResponseBody
    public Map<String,String> editEmp(String oper){
            System.out.println("oper:"+oper);
            .......
            return status;
    }
    
  • 工具栏和其他属性

    <script>
            $(function () {
                $('#tt').jqGrid({
                    url:'/emp/findAllEmp',
                    datatype:'json',
                    colNames:['ID','Username','Mobile','DeptName'],
                    cellEdit:true,
                    editurl:'/emp/editEmp',
                    colModel:[
                        {name:'id'},
                        {name:'username',editable:true},
                        {name:'mobile',editable:true},
                        {name:'deptName',editable:true}
                    ],
                    autowidth:true,   //自动计算列宽(根据父容器的大小)
                    pager:'#pg',   //指定分页工具栏
                    rowList:[5,10,15,20,50],   //每页显示条数的选项
                    rowNum:5,   //默认每页显示的条数
                    page:1,   //默认显示第几页
                    viewrecords:true,   //是否显示信息的总记录数
                    toolbar:['true','both'],    //用来指定表格的工具栏
                    sortname:'id',  //指定默认的排序字段
                    sortorder:'desc',   //指定默认的排序规则
                    caption:'员工信息展示',   //表格标题
                    height:300, //表格宽度
                    prmNames:{'search':'sch'},  //自定义默认请求参数的key
                    rownumbers:true,    //在第一列前显示行号
                    hiddengrid:false,   //初始状态是否显示表格内容
                    hidegrid:true,  //是否显示表格的折叠按钮
                }).navGrid('#pg',{},{closeAfterEdit:true},{closeAfterAdd:true},{},
                    {
                        sopt:['lt','eq']
                    });
                //在工具栏中加入元素
                $('#t_tt').append($('<input type="text">')).append($('<input type="button" value="搜索">'));
            });
    </script>
    
Bootstrap整合jqGrid
  • 常用事件使用方式

                     /**
                     * @param rowid 当前行id
                     * @param iRow  当前行索引位置
                     * @param iCol  当前单元格位置索引
                     * @param e     event对象
                     */
                    ondblClickRow:function(rowid,iRow,iCol,e){  //双击时触发
                        console.log(rowid, iRow, iCol, e);
                    },
                    /**
                     * @param aRowids   所有选中行的id集合,为一个数组
                     * @param status    boolean变量说明checkbox的选择状态,true选中false反之
                     * 无论checkbox是否选择,aRowids始终有值
                     */
                    onSelectAll:function(aRowids,status){   //multiselect为true且点击头部的checkbox时触发此事件
                        console.log(aRowids,status);
                    },
                    /** 当multiselect为true时此参数可用
                     * @param rowid  当前行id
                     * @param status    选择状态,true选中false反之
                     */
                    onSelectRow:function(rowid,status){ //当选择行时触发此事件,即点击第一列的checkbox时触发
                        console.log(rowid, status);
                    }
    
  • 常用方法的使用

    • 方法调用方式

      $('#tt').jqGrid('方法名',参数列表...);
      
    • 常用方法

      $('#tt').jqGrid('getGridParam','selrow');	//返回最后一个选中行的id
      $('#tt').jqGrid('getGridParam','selarrrow');	//返回所有行的id
      $('#tt').jqGrid('delRowData',300);	//根据行数据的id值删除,不会从数据库删除
      $('#tt').jqGrid('getDataIDs');	//返回当前页信息的所有id
      $('#tt').jqGrid('getRowData');	//返回当前页所有行的数据对象数组
      $('#tt').jqGrid('getRowData',300);	//返回指定id的行数据对象
      
  • 事件使用方式和方式的使用演示

    <script>
            $(function () {
                $('#tt').jqGrid({
                    styleUI:'Bootstrap',    //用于整合bootstrap的样式
                    url:'/emp/findAllEmp',
                    datatype:'json',
                    colNames:['编号','姓名','手机号','部门名称'],
                    cellEdit:true,
                    colModel:[
                        {name:'id'},
                        {name:'username',editable:true},
                        {name:'mobile',editable:true},
                        {name:'dept.id',editable:true}
                    ],
                    autowidth:true,
                    pager:'#pg',
                    rowList:[5,10,15,20,50],
                    rowNum:5,
                    page:1,
                    viewrecords:true,
                    editurl:'/emp/editEmp',
                    toolbar:['true','top'],
                    caption:'信息展示',
                    rownumbers:true,
                    multiselect:true,
                    //事件使用方式
                    /**
                     * @param rowid 当前行id
                     * @param iRow  当前行索引位置
                     * @param iCol  当前单元格位置索引
                     * @param e     event对象
                     */
                    ondblClickRow:function(rowid,iRow,iCol,e){  //双击时触发
                        console.log(rowid, iRow, iCol, e);
                    },
                    /**
                     * @param aRowids   所有选中行的id集合,为一个数组
                     * @param status    boolean变量说明checkbox的选择状态,true选中false反之
                     * 无论checkbox是否选择,aRowids始终有值
                     */
                    onSelectAll:function(aRowids,status){   //multiselect为true且点击头部的checkbox时触发此事件
                        console.log(aRowids,status);
                    },
                    /** 当multiselect为true时此参数可用
                     * @param rowid  当前行id
                     * @param status    选择状态,true选中false反之
                     */
                    onSelectRow:function(rowid,status){ //当选择行时触发此事件,即点击第一列的checkbox时触发
                        console.log(rowid, status);
                    }
                }).navGrid('#pg',{
                    //控制工具栏是否展示
                    refresh:false
                },{//编辑工具修饰
                    closeAfterEdit:true
                },{//添加工具的修饰
                    closeAfterAdd: true,
                    //使用覆盖的方式,可以让实体类中的id可以为Integer类型,只是为了不让报错而已
                    editData:{id:''}    //在提交表单的同时,发送额外的请求参数,如果请求参数的key与表单提交数据中的key相同,会覆盖掉表单原始传递的数据
                },{
                    //删除工具的修饰
                },{//搜索工具的修饰
                    closeAfterSearch:true
                });
                //在顶部工具栏自定义搜索框
                $('#t_tt')
                    .append($('<input type="text" id="sch_name" class="form-control" placeholder="请输入搜索条件" style="width: 200px;display: inline;">'))
                    .append($('<button type="button" class="btn btn-info" style="display: inline;">搜索</button>'))
                    .append($('<button type="button" class="btn btn-success" style="display: inline" id="btn">方法测试</button>'))
                //方法测试
                $('#btn').click(function(){
                    //返回最后一个选中行的id
                    let selRowId = $('#tt').jqGrid('getGridParam','selrow');
                    console.log(selRowId);
                    //返回所有选中行的id
                    let selAllRowId = $('#tt').jqGrid('getGridParam','selarrrow');
                    console.log(selAllRowId);
                    //根据行数据的id值删除行,不会从数据库删除
                    $('#tt').jqGrid('delRowData', 1);
                    //返回当前页信息的所有id
                    let currentPageIds = $('#tt').jqGrid('getDataIDs');
                    console.log(currentPageIds);
                    //返回当前页所有行的数据对象数组
                    let getRowDatas = $('#tt').jqGrid('getRowData');
                    console.log(getRowDatas);
                    //返回指定id的行数据对象
                    let getRowData = $('#tt').jqGrid('getRowData',2);
                    console.log(getRowData);
                })
            });
    </script>
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值