layui 數(shù)據(jù)表格+分頁(yè)+搜索+checkbox+緩存選中項(xiàng)數(shù)據(jù)的方法
在做數(shù)據(jù)表格的時(shí)候遇到了很多坑, 今天整理一下方便以后使用.
主要功能是使用數(shù)據(jù)表格, 做分頁(yè),做搜索, 還有checkbox, 支持全選.
當(dāng)選中一些數(shù)據(jù)的時(shí)候, 數(shù)據(jù)切換頁(yè)面數(shù)據(jù)在切換回來(lái)后,選中狀態(tài)就消失了, 我們希望切換回來(lá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 " style="width: 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="width:100%">
<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í)候沒(méi)有得到數(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: { //分頁(yè)設(shè)定
layout: ['count', 'prev', 'page', 'next'] //自定義分頁(yè)布局
, curr: 1 //設(shè)定初始在第 1 頁(yè)
, limit: 10//每頁(yè)多少數(shù)據(jù)
, groups: 5 //只顯示 5 個(gè)連續(xù)頁(yè)碼
},
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)前頁(yè)數(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)前頁(yè)碼
console.log(curr);
//得到數(shù)據(jù)總量
console.log(count);
}
});
//復(fù)選框選中監(jiān)聽(tīng),將選中的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 頁(yè)開(kāi)始
}
, 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":""
}
//效果:

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)聽(tīng)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)前頁(yè)面所有數(shù)據(jù)
for(var i=0;i<table_data.length;i++){
//數(shù)據(jù)中有不存在于不在緩存中則加入緩存中 isInArray該方法來(lái)自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)前頁(yè)面所有數(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)前頁(yè)面所有數(shù)據(jù)
for(var i=0;i<table_data.length;i++){
//如果有數(shù)據(jù)存在與緩存中則刪除
if(isInArray(ids,table_data[i].id)==true){
//removeByValue該方法來(lái)自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;
}
}
}
以上這篇layui 數(shù)據(jù)表格+分頁(yè)+搜索+checkbox+緩存選中項(xiàng)數(shù)據(jù)的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
JavaScript中你不得不知道的Promise高級(jí)用法分享
在JavaScript中,Promise是一種解決異步編程問(wèn)題的重要方式,本文主要來(lái)和大家探討一下23個(gè)Promise的高級(jí)用法,每一個(gè)都在JavaScript的海洋中航行,讓開(kāi)發(fā)者們能夠以更高效、優(yōu)雅的方式處理異步操作,希望對(duì)大就有所幫助2023-12-12
js 兩數(shù)組去除重復(fù)數(shù)值的實(shí)例
下面小編就為大家分享一篇js 兩數(shù)組去除重復(fù)數(shù)值的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2017-12-12
JS自定義函數(shù)對(duì)web前端上傳的文件進(jìn)行類型大小判斷
這篇文章主要介紹了JS自定義函數(shù)對(duì)web前端上傳的文件進(jìn)行類型大小判斷的相關(guān)資料,需要的朋友可以參考下2016-10-10
如何利用js根據(jù)坐標(biāo)判斷構(gòu)成單個(gè)多邊形是否合法
這篇文章主要給大家介紹了關(guān)于如何利用js根據(jù)坐標(biāo)判斷構(gòu)成單個(gè)多邊形是否合法的相關(guān)資料,文章通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2022-01-01
js輸出數(shù)據(jù)精確到小數(shù)點(diǎn)后n位代碼
要保留小數(shù)點(diǎn)后N位的問(wèn)題,經(jīng)過(guò)一番思索,終于解決了,這篇文章主要介紹了js輸出數(shù)據(jù)精確到小數(shù)點(diǎn)后n位代碼,感興趣的朋友可以參考一下2016-07-07
原生JS和JQuery動(dòng)態(tài)添加、刪除表格行的方法
這篇文章主要介紹了原生JS和JQuery動(dòng)態(tài)添加、刪除表格行的方法,涉及javascript針對(duì)頁(yè)面元素的動(dòng)態(tài)操作技巧,需要的朋友可以參考下2015-05-05

