溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

layui中數(shù)據(jù)表格+分頁+搜索+checkbox+緩存選中項(xiàng)數(shù)據(jù)的示例分析

發(fā)布時(shí)間:2021-07-20 11:40:02 來源:億速云 閱讀:166 作者:小新 欄目:web開發(fā)

這篇文章主要介紹了layui中數(shù)據(jù)表格+分頁+搜索+checkbox+緩存選中項(xiàng)數(shù)據(jù)的示例分析,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

主要功能是使用數(shù)據(jù)表格, 做分頁,做搜索, 還有checkbox, 支持全選.

當(dāng)選中一些數(shù)據(jù)的時(shí)候, 數(shù)據(jù)切換頁面數(shù)據(jù)在切換回來后,選中狀態(tài)就消失了, 我們希望切換回來的時(shí)候, 選中狀態(tài)還能存在, 因此做了個(gè)緩存, 使checkbox 保持選中狀態(tài).代碼如下:

1.HTML 搜索輸入框

<form class="layui-form">
 <div class="layui-input-inline">
  <input type="tel" name="searContent" autocomplete="off"
    placeholder="姓名/手機(jī)/身份證" class="layui-input">
 </div>
</form>

2.HTML 搜索按鈕

<div class="layui-input-inline " >
 <button class="layui-btn" id="searchEmailCompany" data-type="reload">
  <i class="layui-icon" ></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" >
       <div class="user-tables">
        <table id="userTables" lay-filter="userTables"> </table>
       </div>
      </div>
     </div>
    </section>
   </div>
  </div>
 </div>
</div>

4.HTML 時(shí)間格式轉(zhuǎn)換

<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 功能設(shè)定

<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;
  //記錄選中的數(shù)據(jù):做緩存使用,作為參數(shù)傳遞給后臺(tái),然后生成pdf ,壓縮
  var ids =new Array();
  //當(dāng)前表格中的全部數(shù)據(jù):在表格的checkbox全選的時(shí)候沒有得到數(shù)據(jù), 因此用全局存放變量
  var table_data=new Array();
  
     var a = table.render({
   elem: "#userTables",
   skin: 'line', //行邊框風(fēng)格
   cols: [[
    {checkbox: true, width: 60, fixed: true},
    {type: 'numbers', title: '序號(hào)', width: '40'},
    {
     field: "name",
     width: 80,
     title: "姓名",
     align: "left"
    }, {
     field: "phone",
     width: 120,
     title: "電話",
     align: "left"
    }, {
     field: "identificationNuber",
     width: 170,
     title: "身份證號(hào)碼",
     align: "left"
    }, {
     field: "updateTime",
     width: 140,
     title: "更新時(shí)間",
     align: "left",
     templet: '#TimeTpl'
    }, {
     title: "常用操作",
     width: 200,
     align: "left",
     toolbar: "#userbar",
     fixed: "right"
    }]],
   url: "/user/getReportList",
//   data: userData,
   page: { //分頁設(shè)定
    layout: ['count', 'prev', 'page', 'next'] //自定義分頁布局
    , curr: 1 //設(shè)定初始在第 1 頁
    , limit: 10//每頁多少數(shù)據(jù)
    , groups: 5 //只顯示 5 個(gè)連續(xù)頁碼
   },
   even: true
   ,done: function(res, curr, count){
    //數(shù)據(jù)表格加載完成時(shí)調(diào)用此函數(shù)
    //如果是異步請(qǐng)求數(shù)據(jù)方式,res即為你接口返回的信息。
    //如果是直接賦值的方式,res即為:{data: [], count: 99} data為當(dāng)前頁數(shù)據(jù)、count為數(shù)據(jù)總長(zhǎng)度

     //設(shè)置全部數(shù)據(jù)到全局變量
     table_data=res.data;
 
     //在緩存中找到id ,然后設(shè)置data表格中的選中狀態(tài)
     //循環(huán)所有數(shù)據(jù),找出對(duì)應(yīng)關(guān)系,設(shè)置checkbox選中狀態(tài)
     for(var i=0;i< res.data.length;i++){
      for (var j = 0; j < ids.length; j++) {
       //數(shù)據(jù)id和要勾選的id相同時(shí)checkbox選中
       if(res.data[i].id == ids[j])
       {
        //這里才是真正的有效勾選
        res.data[i]["LAY_CHECKED"]='true';
        //找到對(duì)應(yīng)數(shù)據(jù)改變勾選樣式,呈現(xiàn)出選中效果
        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');
       }
      }
     }
     //設(shè)置全選checkbox的選中狀態(tài),只有改變LAY_CHECKED的值, table.checkStatus才能抓取到選中的狀態(tài)
     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');
     }
    //得到所有數(shù)據(jù)
    console.log(res);
    //得到當(dāng)前頁碼
    console.log(curr);
    //得到數(shù)據(jù)總量
    console.log(count);
   }
  });

  //復(fù)選框選中監(jiān)聽,將選中的id 設(shè)置到緩存數(shù)組,或者刪除緩存數(shù)組
  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);
       }
      }
     }
    }
   }
  });

  //搜索加載--數(shù)據(jù)表格重載
  var $ = layui.$, active = {
   reload: function () {
    //執(zhí)行重載
    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();
 });

//刪除數(shù)組自定義函數(shù)
 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. 請(qǐng)求數(shù)據(jù)格式

//請(qǐng)求的數(shù)據(jù)格式

{
  "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":"周*謹(jǐn)",
      "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":""
}

//效果:

layui中數(shù)據(jù)表格+分頁+搜索+checkbox+緩存選中項(xiàng)數(shù)據(jù)的示例分析

7.后臺(tái)java

(1).controller

/**
 * 獲取報(bào)告列表
 *
 *@return
 */
@RequestMapping(value = "/getReportList", method = {RequestMethod.GET})
@ResponseBody
public Map getReportList( Integer page , Integer limit ,String searContent) {
 logger.info("獲取報(bào)告列表");
 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("獲取報(bào)告列表 錯(cuò)誤",e);
 }
 logger.error("獲取報(bào)告列表");
 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

<!-- 查詢所有報(bào)告列表 -->
 <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>
 <!-- 查詢所有報(bào)告列表 總數(shù) -->
<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網(wǎng)友解決方案(未測(cè)):

//實(shí)例
  layui.use(['table','form'], function(){

    var form = layui.form; 
//form監(jiān)聽checkbox事件
  form.on('checkbox', function(obj){ 
  //當(dāng)前元素
  var data = $(obj.elem);
  //遍歷父級(jí)tr,取第一個(gè),然后查找第二個(gè)td,取值 轉(zhuǎn)換為Number
  var id = Number(data.parents('tr').first().find('td').eq(1).text());
   //選中or未選中
  var check = obj.elem.checked; 
   //復(fù)選框狀態(tài)
  // var checkStatus = table.checkStatus('users');
  //如果選中
  if(check==true){    
  //如果緩存數(shù)組存在值
   if(ids.length>0){    
   //id==0便是全選按鈕
   if(id==0){  
    //循環(huán)當(dāng)前頁面所有數(shù)據(jù)
    for(var i=0;i<table_data.length;i++){  
     //數(shù)據(jù)中有不存在于不在緩存中則加入緩存中 isInArray該方法來自common.js
    if(isInArray(ids,table_data[i].id)==false){
      ids.push(table_data[i].id); 
     }
    }    
   }else{
    //單選中的數(shù)據(jù)不在緩存中則加入緩存中
    if(isInArray(ids,id)==false){
     ids.push(id); 
    }
   }
  //如果緩存數(shù)組不存在值 表示第一次添加
  }else{  
   //id==0便是全選按鈕
    if(id==0){   
     //循環(huán)當(dāng)前頁面所有數(shù)據(jù)直接加入緩存
     for(var i=0;i<table_data.length;i++){     
      ids.push(table_data[i].id);    
     }
    }else{   
     //單選中的數(shù)據(jù)加入緩存中
     ids.push(id);     
     }   
  } 
  //取消選中 
  }else{
   //id==0便是全選按鈕
   if(id==0){
    //循環(huán)當(dāng)前頁面所有數(shù)據(jù)
    for(var i=0;i<table_data.length;i++){  
     //如果有數(shù)據(jù)存在與緩存中則刪除
     if(isInArray(ids,table_data[i].id)==true){
      //removeByValue該方法來自common.js
      ids.removeByValue(table_data[i].id); 
     }
     }
   }else{
    //如果單選中的數(shù)據(jù)存在與緩存中則刪除
    if(isInArray(ids,id)==true){
     ids.removeByValue(id);
     }
   } 
  }
 }); 

})

//判斷數(shù)組中是否存在元素 arr數(shù)組 value需判斷的元素
function isInArray(arr, value) {
 for (var i = 0; i < arr.length; i++) {
  if (value === arr[i]) {
   return true;
  }
 }

 return false;
}

// 數(shù)組對(duì)象增加刪除方法 數(shù)組.removeByValue(需刪除的值)即可調(diào)用
Array.prototype.removeByValue = function(val) {
 for (var i = 0; i < this.length; i++) {
  if (this[i] == val) {
   this.splice(i, 1);
   break;
  }
 }
}

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“l(fā)ayui中數(shù)據(jù)表格+分頁+搜索+checkbox+緩存選中項(xiàng)數(shù)據(jù)的示例分析”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI