• layui 数据表格+分页+搜索+checkbox+缓存选中项数据


      在做数据表格的时候遇到了很多坑, 今天整理一下方便以后使用.

      主要功能是使用数据表格, 做分页,做搜索,  还有checkbox,  支持全选.

      当选中一些数据的时候, 数据切换页面数据在切换回来后,选中状态就消失了, 我们希望切换回来的时候, 选中状态还能存在, 因此做了个缓存, 使checkbox 保持选中状态.代码如下:

    1.HTML  搜索输入框

    <form class="layui-form">
        <div class="layui-input-inline">
            <input type="tel" name="searContent" autocomplete="off"
                   placeholder="姓名/手机/身份证" class="layui-input">
        </div>
    </form>

    2.HTML  搜索按钮

    <div class="layui-input-inline " style=" 90px">
        <button class="layui-btn" id="searchEmailCompany" data-type="reload">
            <i class="layui-icon" style="font-size: 20px; "></i> 搜索
        </button>
    </div>

    3.HTML  table表格

    <div class="yys-fluid yys-wrapper">
            <div class="layui-row lay-col-space20">
                <div class="layui-cos-xs12 layui-col-sm12 layui-col-md12 layui-col-lg12">
                    <section class="yys-body animated rotateInDownLeft">
                        <div class="yys-body-content clearfix changepwd">
                            <div class="layui-col-lg12 layui-col-md10 layui-col-sm12 layui-col-xs12" style="100%">
                                <div class="user-tables">
                                    <table id="userTables" lay-filter="userTables"> </table>
                                </div>
                            </div>
                        </div>
                    </section>
                </div>
            </div>
        </div>
    </div>

    4.HTML  时间格式转换

    <script type="text/html" id="TimeTpl">
        {{#
        var parseDate= function(date){
        if(date){
        var t=new Date(date);
        return t.getFullYear()+"-"+(t.getMonth()+1)+"-"+t.getDate()+" "+t.getHours()+":"+t.getMinutes();
        }
        }
        }}
        {{parseDate(d.updateTime)}}
    </script>

    5. js  功能设定

    <script>
        var $ = null;
        layui.use(["jquery", "upload", "form", "table", "layer", "element", "laydate"], function () {
            $ = layui.jquery;
            var element = layui.element,
                layer = layui.layer,
                upload = layui.upload,
                form = layui.form,
                laydate = layui.laydate,
                table = layui.table;
            //记录选中的数据:做缓存使用,作为参数传递给后台,然后生成pdf ,压缩
            var ids =new Array();
            //当前表格中的全部数据:在表格的checkbox全选的时候没有得到数据, 因此用全局存放变量
            var table_data=new Array();
          
        
    var a = table.render({ elem: "#userTables", skin: 'line', //行边框风格 cols: [[ {checkbox: true, 60, fixed: true}, {type: 'numbers', title: '序号', '40'}, { field: "name", 80, title: "姓名", align: "left" }, { field: "phone", 120, title: "电话", align: "left" }, { field: "identificationNuber", 170, title: "身份证号码", align: "left" }, { field: "updateTime", 140, title: "更新时间", align: "left", templet: '#TimeTpl' }, { title: "常用操作", 200, align: "left", toolbar: "#userbar", fixed: "right" }]], url: "/user/getReportList", // data: userData, page: { //分页设定 layout: ['count', 'prev', 'page', 'next'] //自定义分页布局 , curr: 1 //设定初始在第 1 页 , limit: 10//每页多少数据 , groups: 5 //只显示 5 个连续页码 }, even: true ,done: function(res, curr, count){ //数据表格加载完成时调用此函数 //如果是异步请求数据方式,res即为你接口返回的信息。 //如果是直接赋值的方式,res即为:{data: [], count: 99} data为当前页数据、count为数据总长度 //设置全部数据到全局变量 table_data=res.data; //在缓存中找到id ,然后设置data表格中的选中状态 //循环所有数据,找出对应关系,设置checkbox选中状态 for(var i=0;i< res.data.length;i++){ for (var j = 0; j < ids.length; j++) { //数据id和要勾选的id相同时checkbox选中 if(res.data[i].id == ids[j]) { //这里才是真正的有效勾选 res.data[i]["LAY_CHECKED"]='true'; //找到对应数据改变勾选样式,呈现出选中效果 var index= res.data[i]['LAY_TABLE_INDEX']; $('.layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true); $('.layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked'); } } } //设置全选checkbox的选中状态,只有改变LAY_CHECKED的值, table.checkStatus才能抓取到选中的状态 var checkStatus = table.checkStatus('my-table'); if(checkStatus.isAll){ $(' .layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true); $('.layui-table-header th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked'); } //得到所有数据 console.log(res); //得到当前页码 console.log(curr); //得到数据总量 console.log(count); } }); //复选框选中监听,将选中的id 设置到缓存数组,或者删除缓存数组 table.on('checkbox(userTables)', function (obj) { if(obj.checked==true){ if(obj.type=='one'){ ids.push(obj.data.id); }else{ for(var i=0;i<table_data.length;i++){ ids.push(table_data[i].id); } } }else{ if(obj.type=='one'){ for(var i=0;i<ids.length;i++){ if(ids[i]==obj.data.id){ ids.remove(i); } } }else{ for(var i=0;i<ids.length;i++){ for(var j=0;j<table_data.length;j++){ if(ids[i]==table_data[j].id){ ids.remove(i); } } } } } }); //搜索加载--数据表格重载 var $ = layui.$, active = { reload: function () { //执行重载 table.reload('userTables', { page: { curr: 1 //重新从第 1 页开始 } , where: { searContent: $("input[name=searContent]").val() } }); } };

    $(
    '#searchEmailCompany').on('click', function () { ids=new Array(); var type = $(this).data('type'); active[type] ? active[type].call(this) : ''; }); element.init(); }); //删除数组自定义函数 Array.prototype.remove=function(dx) { if(isNaN(dx)||dx>this.length){return false;} for(var i=0,n=0;i<this.length;i++) { if(this[i]!=this[dx]) { this[n++]=this[i] } } this.length-=1 } </script>

    6. 请求数据格式

     

    //请求的数据格式

    {
      "code":0,
      "count":39,
      "data":[
        {
          "id":57,
          "insertTime":1513578156000,
          "leaguerId":65,
          "phone":"1356***98907",
          "status":0,
          "updateTime":1513578156000,
          "uuid":"7c94e354-cd87-4ea7-bccf-2e115e1cbc49"
        },
        {
          "id":56,
          "identificationNuber":"652101**3*",
          "insertTime":1513578013000,
          "leaguerId":60,
          "name":"周*谨",
          "phone":"135**907",
          "status":0,
          "updateTime":1513578037000,
          "uuid":"ed91fac6-56f8-4771-aa79-32863a27bf6f"
        },
        {
          "id":55,
          "identificationNuber":"42098**",
          "insertTime":1513576647000,
          "leaguerId":60,
          "name":"董*",
          "phone":"1356**8908",
          "status":0,
          "updateTime":1513576729000,
          "uuid":"62d58c68-b49f-44f4-b5a3-e8ea629b5d32"
        },
        {
          "id":54,
          "identificationNuber":"6501**",
          "insertTime":1513576558000,
          "leaguerId":60,
          "name":"*光",
          "phone":"158009**059",
          "status":0,
          "updateTime":1513576590000,
          "uuid":"a65e3880-f44c-44cb-9f78-f7d7bbacee86"
        },
    
        {
          "id":53,
          "identificationNuber":"310114**",
          "insertTime":1513576261000,
          "leaguerId":60,
          "name":"吴*雯",
          "phone":"137**5261",
          "status":0,
          "updateTime":1513576294000,
          "uuid":"6a0766f1-da1d-4c55-8bd5-5dd7a6ad7cd3"
        },
        {
          "id":52,
          "identificationNuber":"3201**",
          "insertTime":1513574849000,
          "leaguerId":65,
          "name":"*骏",
          "phone":"186**9521",
          "status":0,
          "updateTime":1513574998000,
          "uuid":"89f1fddf-d3c2-4a3b-8a13-c501bdb8e22c"
        },
    
        {
          "id":51,
          "insertTime":1513562761000,
          "leaguerId":63,
          "phone":"15655**110",
          "status":0,
          "updateTime":1513562761000,
          "uuid":"f4a3b875-d15c-423b-836b-9123cde96000"
        },
        {
          "id":49,
          "identificationNuber":"4210**",
          "insertTime":1513561354000,
          "leaguerId":63,
          "name":"余*",
          "phone":"1527**4673",
          "status":0,
          "updateTime":1513561843000,
          "uuid":"b38a8660-bf74-41b9-b01f-6e79189327a3"
        },
        {
          "id":50,
          "insertTime":1513561498000,
          "leaguerId":63,
          "phone":"186**59965",
          "status":0,
          "updateTime":1513561498000,
          "uuid":"445cd1dc-bd75-4a4e-933d-646e9823647a"
        },
        {
          "id":48,
          "insertTime":1513516215000,
          "leaguerId":63,
          "phone":"1356**8907",
          "status":0,
          "updateTime":1513516215000,
          "uuid":"706851f6-9243-4ea9-97eb-fc8e12c42c77"
        }
      ],
      "msg":""
    }

     //效果:

    7.后台java  

    (1).controller

    /**
     * 获取报告列表
     *
     *@return
     */
    @RequestMapping(value = "/getReportList", method = {RequestMethod.GET})
    @ResponseBody
    public Map getReportList( Integer page ,  Integer limit ,String searContent) {
        logger.info("获取报告列表");
        if (SecurityUtils.getSubject().isAuthenticated() == false) {
            logger.error("未登录");
            return null;
        }
        System.out.println(searContent);
        Map<Object, Object> mapParameter = new HashedMap();
        mapParameter.put("page", (page-1)*10);
        mapParameter.put("limit", limit);
        mapParameter.put("searContent", searContent);
        try {
            List<Report> vReports=reportService.findReportList(mapParameter);
           Integer count=reportService.findReportListCount(mapParameter);
            Map<Object, Object> map = new HashedMap();
            map.put("code", 0);
            map.put("msg", "");
            map.put("count", count);
            map.put("data", vReports);
            return map;
        } catch (Exception e) {
            logger.error("获取报告列表 错误",e);
        }
        logger.error("获取报告列表");
        return null;
    }

    (2).Service

    @Override
    public List<Report> findReportList(Map mapParameter) {
        return  reportDao.selectList("findReportList",mapParameter);
    }
    @Override
    public Integer findReportListCount(Map mapParameter) {
       return  reportDao.selectOne("findReportCount",mapParameter);
    }

    (3).mybatis  SQL

    <!-- 查询所有报告列表 -->
     <select id="findReportList" resultMap="BaseResultMap"  parameterType="java.util.Map">
         select *   FROM  report where status=0
         <if test="searContent!=null ">
             and (
             (name LIKE concat(concat("%",#{searContent}),"%"))
             or (phone LIKE concat(concat("%",#{searContent}),"%"))
             or (identification_nuber LIKE concat(concat("%",#{searContent}),"%"))
             )
         </if>
           ORDER BY update_time DESC limit  #{page} , #{limit};
     </select>
     <!-- 查询所有报告列表 总数 -->
    <select id="findReportCount" resultType="java.lang.Integer"  parameterType="java.util.Map">
         select COUNT(*) FROM  report where status=0
        <if test="searContent!=null ">
            and (
            (name LIKE concat(concat("%",#{searContent}),"%"))
            or (phone LIKE concat(concat("%",#{searContent}),"%"))
            or (identification_nuber LIKE concat(concat("%",#{searContent}),"%"))
            )
        </if>
          ;
     </select>

    BUG网友解决方案(未测):

    //实例
            layui.use(['table','form'], function(){
    
                    var form = layui.form;    
    //form监听checkbox事件
           form.on('checkbox', function(obj){    
         //当前元素
           var data = $(obj.elem);
           //遍历父级tr,取第一个,然后查找第二个td,取值  转换为Number
          var id = Number(data.parents('tr').first().find('td').eq(1).text());
              //选中or未选中
           var check = obj.elem.checked;   
              //复选框状态
            //  var checkStatus = table.checkStatus('users');
            //如果选中
           if(check==true){               
            //如果缓存数组存在值
             if(ids.length>0){              
              //id==0便是全选按钮
               if(id==0){       
                 //循环当前页面所有数据
                   for(var i=0;i<table_data.length;i++){       
                       //数据中有不存在于不在缓存中则加入缓存中    isInArray该方法来自common.js
                    if(isInArray(ids,table_data[i].id)==false){
                           ids.push(table_data[i].id);   
                      }
                   }             
               }else{
                   //单选中的数据不在缓存中则加入缓存中
                   if(isInArray(ids,id)==false){
                       ids.push(id);   
                    }
               }
           //如果缓存数组不存在值 表示第一次添加
            }else{       
                //id==0便是全选按钮
                  if(id==0){         
                      //循环当前页面所有数据直接加入缓存
                       for(var i=0;i<table_data.length;i++){                    
                           ids.push(table_data[i].id);                
                       }
                  }else{           
                      //单选中的数据加入缓存中
                       ids.push(id);                 
                      }           
            }    
          //取消选中    
          }else{
              //id==0便是全选按钮
              if(id==0){
                  //循环当前页面所有数据
                  for(var i=0;i<table_data.length;i++){      
                      //如果有数据存在与缓存中则删除
                      if(isInArray(ids,table_data[i].id)==true){
                          //removeByValue该方法来自common.js
                          ids.removeByValue(table_data[i].id);   
                        }
                     }
              }else{
                  //如果单选中的数据存在与缓存中则删除
                  if(isInArray(ids,id)==true){
                      ids.removeByValue(id);
                      }
              } 
          }
       }); 
    
    })
    
    //判断数组中是否存在元素  arr数组   value需判断的元素
    function isInArray(arr, value) {
        for (var i = 0; i < arr.length; i++) {
            if (value === arr[i]) {
                return true;
            }
        }
    
        return false;
    }
    
    // 数组对象增加删除方法 数组.removeByValue(需删除的值)即可调用
    Array.prototype.removeByValue = function(val) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == val) {
                this.splice(i, 1);
                break;
            }
        }
    }

    版权声明: 本文有 ```...裥簞點 发表于 bloghome博客

    转载声明: 可自由转载、引用,但需要属名作者且注明文章出处。

    文章链接: https://www.bloghome.com.cn/user/yysblog

     

  • 相关阅读:
    Oracle 增加修改删除字段
    asp.net,简单权限。存取读XML
    点击按钮出现60秒禁用倒计时js代码
    vb.net 接口POST方式传参数提交返回值
    给VS2005 2008等添加代码对照线,对齐线
    sql 、linq、lambda 查询语句的区别
    C# asp.net 实现导出Excel
    SQL中使用update inner join和delete inner join
    导入EXCEL表时,提示"找不到可安装的ISAM"怎么办
    ASP.NET后台通过输出JavaScript弹出窗口小结 弹窗弹框
  • 原文地址:https://www.cnblogs.com/yysbolg/p/8805959.html
Copyright © 2020-2023  润新知