layui
行点击事件:点了没反应?
//监听行工具事件layui.table.on('tool(demo)', function (obj) {//alert(222) });
原因:检查下id与lay-filter是否一致;id与lay-filter必须一致。
<table id="demo" lay-filter="demo"></table>
【layui】使用table编辑功能,滚动条位置固定不变,无感刷新
使用table 单元格编辑功能时,每次里焦触发成功后手动调用了table.reload函数,导致滚动条初始化到顶部。
- 定义变量
// 重载表格---保持滚动条位置let tableScroll = {scrollTob: 0,scrollLeft: 0,};
- 在table 的done函数中进行表格滚动
done: function (res, curr, count) { // 重载表格---保持滚动条位置$('.layui-table-body').scrollTop(tableScroll.scrollTob);$('.layui-table-body').scrollLeft(tableScroll.scrollLeft);tableScroll.scrollTob = 0;tableScroll.scrollLeft = 0; },
- 在表格编辑后,表格刷新前先记录滚动条位置
// 重载表格---保持滚动条位置var scrollTop = ($('.layui-table-body') && $('.layui-table-body').length > 1) ? $('.layui-table-body')[0].scrollTop : $('.layui-table-body').scrollTop;var scrollLeft = ($('.layui-table-body') && $('.layui-table-body').length > 1) ? $('.layui-table-body')[0].scrollLeft : $('.layui-table-body').scrollLeft;tableScroll.scrollTob = scrollTop == 0 ? tableScroll.scrollTob : scrollTop;tableScroll.scrollLeft = scrollLeft;layui.table.reload('test', { data: productList });
// var tipsValComp;// // 1.找到触发的事件对象(绑定全局) 2.事件处理程序// $('body').on('mouseover', '.hoverPerDay', function () {// var ovText = $(this).text();// // var html = "<p style='word-wrap:break-word;width: 150px;'>" + ovText + "</p>";// var html = `// <div class="hoverDIV_PerDay" style="">// <div class="compName" style="">公司1公司1公司1公司1公司1公司1公司1公司1</div>// <div class="item">// <div>库存:</div>// <div><span class="sub_cont">600 </span> T</div>// </div>// <div class="item">// <div>时间:</div>// <div><span class="sub_cont">2023-08-17</span></div>// </div>// <div class="item">// <div>状态:</div>// <div><span class="sub_cont">正常 </span></div>// </div>// </div>`;// // layer.tips('默认向右', this);// tipsValComp = layer.tips(html, this, { tips: [3, '#fff', 'box-shadow: 0px 0px 6px 1px rgba(0,0,0,0.1);'], time: 0 });// });// //鼠标移出// $('body').on('mouseout', '.hoverPerDay', function () {// layer.close(tipsValComp);// });// var tipsValPerDay;// // 1.找到触发的事件对象(绑定全局) 2.事件处理程序// $('body').on('mouseover', '.hoverPerComp', function () {// var ovText = $(this).text();// // var html = "<p style='word-wrap:break-word;width: 150px;'>" + ovText + "</p>";// var html = `// <div class="hoverDIV_PerComp" style="">// <div class="compName" style="">公司1公司1公司1公司1公司1公司1公司1公司1</div>// <div class="item">// <div>库存容量:</div>// <div><span class="sub_cont">600 </span> T</div>// </div>// <div class="item">// <div>库存上限:</div>// <div><span class="sub_cont">600 </span> T</div>// </div>// <div class="item">// <div>库存下限:</div>// <div><span class="sub_cont">600 </span> T</div>// </div>// <div class="item">// <div>平均每日消耗(估):</div>// <div><span class="sub_cont">600 </span> T</div>// </div>// </div>`;// // layer.tips('默认向右', this);// tipsValPerDay = layer.tips(html, this, { tips: [3, '#fff', 'box-shadow: 0px 0px 6px 1px rgba(0,0,0,0.1);'], time: 0 });// });// //鼠标移出// $('body').on('mouseout', '.hoverPerComp', function () {// layer.close(tipsValPerDay);// });
问题:在时间筛选的时候遇到了难题,表格重载后,表头没有按照重载方法传入的cols参数展示,而是还是展示原先的表头
原因:经过一番排查后发现原因,layui中 table.reload(ID, options) 在接收options中的参数中,如果参数是数组形式,那并不会完全替换历史参数,而是覆盖到对应长度。如果之前传入参数是[1,2,3,4],重载传入参数是[a,b.c],那后台获取到的参数是[a,b,c,4],这就是为什么我在筛选日期为2月后,表头还是展示到30天(新传入的表头29项,和之前的30项合并后,任然是30项)这个问题是真的坑啊
解决:这个问题解决起来并不复杂,而是复杂在了发现问题的原因,实际解决只需要一行关键代码就好,在table的render方法的回调函数中,将cols字段初始化就可以了: this.cols = [ ];
done:function (res,curr,count) {this.cols = []; //(关键代码)将cols初始化,否则表格重载时无法正确重新渲染表头}
table.reload('test', {cols: [cols],where: {"data": encodeURI(JSON.stringify(data.field).replaceAll("\"", "\\\""))},page: {curr: 1}});
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>客户库存</title><meta name="renderer" content="webkit"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta name="viewport"content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0"><link rel="stylesheet" href="../../../layuiadmin/layui/css/layui.css" media="all"><link rel="stylesheet" href="../../../layuiadmin/style/admin.css" media="all"><link rel="stylesheet" href="../../open.css" media="all"><style>.layui-table td,.layui-table th {font-size: 12px !important;}.layui-table-cell {height: 28px;line-height: 28px;padding: 0px !important;}.layui-table-view .layui-table td,.layui-table-view .layui-table th {padding: 0 !important;}.layui-layer-content {width: fit-content !important;}</style>
</head><body><div class="layui-fluid"><div class="layui-row layui-col-space15"><div class="layui-col-md12"><div class="layui-card" style=""><div class="layui-card-body"><form class="layui-form layui-form-pane" action=""><div class="layui-form-item"><div class="layui-inline"><label class="layui-form-label">客户</label><div class="layui-input-inline"><input type="text" id="supplyName" name="supplyName" autocomplete="off" class="layui-input"placeholder="请输入客户"><input type="text" id="supply" name="supply" style="display:none;"></div></div><div class="layui-inline"><label class="layui-form-label">月份</label><div class="layui-input-inline"><input type="text" id="currMonth" name="currMonth" autocomplete="off" class="layui-input"placeholder="选择月份"></div></div><div class="layui-inline"><button type="button" class="layui-btn layui-btn layui-btn-normal" lay-submit lay-filter="search"><i class="layui-icon"></i>搜索</button><button type="reset" class="layui-btn layui-btn layui-btn-danger"><i class="layui-icon"></i>重置</button></div><!-- 图例 --><div class="lenged_box"><div class="lenged_item"><div class="lenged_up"></div><div>超过上限</div></div><div class="lenged_item"><div class="lenged_down"></div><div>超过下限</div></div><div class="lenged_item"><div class="lenged_today"></div><div>今日时间</div></div><div class="lenged_item"><div class="lenged_prev"></div><div>预测时间</div></div></div></div></form><div class="layui-row" style=""><table class="layui-hide" id="test" lay-filter="test"></table></div></div></div></div></div></div><script src="../../../layuiadmin/layui/layui.all.js"></script><script src="../../utils.js"></script><script type="text/javascript">// 设置卡片高度$('.layui-card-body').css('height', $(window).height() - 32);//执行一个laydate实例layui.laydate.render({elem: '#currMonth',type: 'month',});// 获取表头 // var d = {// fn: "customerAction",// md: "selectCustomerInvTitleList"// }// httpRequestPost("/MngServlet", d, function (res) {// console.log(res);// if (res.rt == 0) {// var cols = res.data;// // 获取data// layui.table.render({// id: 'test',// elem: '#test',// title: '入库计划单',// height: 'full-80',// url: contextPath + '/MngServlet',// method: 'post',// where: {// fn: "customerAction",// md: "selectCustomerInvList"// },// contentType: 'application/json',// parseData: function (res) { //res 即为原始返回的数据// return {// "code": res.rt, //解析接口状态// "data": res.data, //解析数据列表// "count": res.count,// "msg": res.msg// };// },// cols: cols,// done: function (res, curr, count, origin) {// // 获取所有表头// var totalArr = $('.layui-table-header th');// var today = 999;//今日日期// totalArr.each(function (index, item) {// var currTh = $(this).attr('data-field').split('num')[1];//获取表头的data-field:num28// const date = new Date().getDate();//// if (Number(currTh) === Number(date)) {// // 相等就是今日// today = index;//赋值今日// $(this).css({ 'background': '#1e9fff', 'color': '#fff', })// } else if (index > today) {// // 大于今日就是未来// $(this).css({ 'background': '#daf6e1', 'color': '#333333', 'border-bottom': '2px solid #00BF39', 'box-sizing': 'border-box' })// }// });// }// });// }// })// // td上下限颜色// function tdColor (title, up, lower, num, d) {// if (title >= up) {// return `<div class="hoverPerDay" id="tdPerDay${d.customerId}${num}" οnmοuseοver="showPerDay(${title}, ${up}, ${lower},${num},${d.customerId},'${d.customerName}');" οnmοuseleave="closeTipsPerDay();" style="background:#ffcdce;color:#ff3839"> ${title}</div> `// }// if (title <= lower) {// return `<div class="hoverPerDay" id="tdPerDay${d.customerId}${num}" οnmοuseοver="showPerDay(${title},${up}, ${lower},${num},${d.customerId},'${d.customerName}');" οnmοuseleave="closeTipsPerDay();" style="background:#ffecc6;color:#ff9202"> ${title}</div> `// }// return `<div class="hoverPerDay" id="tdPerDay${d.customerId}${num}" οnmοuseοver="showPerDay(${title}, ${up}, ${lower},${num},${d.customerId},'${d.customerName}');" οnmοuseleave="closeTipsPerDay();"> ${title}</div> `// }// // td公司// function tdComp (d) {// return `<div class="hoverPerComp" id="tdPerDay${d.customerId}" οnmοuseοver="showComp('${d.customerName}',${d.customerId},${d.invLimit}, ${d.invUp}, ${d.invLow},${d.invDaily});" οnmοuseleave="closeTipsComp();"><div class="">${d.customerName}</div><img src="../../img/icon/charts.png" alt=""></div>`// }function checkDate (params) {if (params < 10) {params = "0" + params;} else {params = params + "";}return params}let daysList = [];let cols = [];let queryYear = new Date().getFullYear(); //默认获取当前年;//需要查询的年份let queryMonth = checkDate(new Date().getMonth() + 1); //默认获取当前月;//需要查询的月份getCurrMonthDays(queryYear, queryMonth);//自动显示本月日期function getCurrMonthDays (year, month) {daysList = [];cols = [];//获取当前月有多少天let day = new Date(year, month, 0).getDate();let current_month_days = [];for (let i = 0; i < day; i++) {let d = i + 1;if (d < 10) {current_month_days[i] = parseInt("0" + d);} else {current_month_days[i] = d;}}// console.log("月份测试", current_month_days);daysList = current_month_days;for (let a = 0; a < daysList.length; a++) {cols.push({title: `${daysList[a]} `,width: "50",align: "center",field: `num${daysList[a]}`,// templet: `<div>{{tdColor(d.num${daysList[a]}, d.invUp, d.invLow,${daysList[a]}, d)}</div> `,templet: function (d) {var s = 'num' + daysList[a];var title = d[s];//当前单元格的数值if (d.title >= d.invUp) {return `<div class="hoverPerDay" id="tdPerDay${d.customerId}${daysList[a]}" οnmοuseοver="showPerDay(${title}, ${d.invUp}, ${d.invLow},${daysList[a]},${d.customerId},'${d.customerName}');" οnmοuseleave="closeTipsPerDay();" style="background:#ffcdce;color:#ff3839"> ${title}</div> `}if (d.title <= d.invLow) {return `<div class="hoverPerDay" id="tdPerDay${d.customerId}${daysList[a]}" οnmοuseοver="showPerDay(${title},${d.invUp}, ${d.invLow},${daysList[a]},${d.customerId},'${d.customerName}');" οnmοuseleave="closeTipsPerDay();" style="background:#ffecc6;color:#ff9202"> ${title}</div> `}return `<div class="hoverPerDay" id="tdPerDay${d.customerId}${daysList[a]}" οnmοuseοver="showPerDay(${title}, ${d.invUp}, ${d.invLow},${daysList[a]},${d.customerId},'${d.customerName}');" οnmοuseleave="closeTipsPerDay();"> ${title}</div> `},})}cols.unshift({ title: "序号", type: "numbers", width: "40" },{field: "customerName", title: '客户名称', width: "90", event: "openCompCharts",templet: "<div>{{tdComp(d)}}</div>",templet: function (d) {return `<div class="hoverPerComp" id="tdPerDay${d.customerId}" οnmοuseοver="showComp('${d.customerName}',${d.customerId},${d.invLimit}, ${d.invUp}, ${d.invLow},${d.invDaily});" οnmοuseleave="closeTipsComp();"><div class="">${d.customerName}</div><img src="../../img/icon/charts.png" alt=""></div>`}});};// hoverPerDay var tipsPerDay;function showPerDay (title, up, lower, num, customerId, customerName) {// console.log(title, up, lower, num, customerId, customerName);// console.log('显示的信息');var currYM = new Date().toLocaleDateString().split('/')[0] + '-' + new Date().toLocaleDateString().split('/')[1] + '-';//'2023/8/2'var html = `<div class="hoverDIV_PerDay"><div class="compName">${customerName}</div><div class="item"><div>库存:</div><div><span class="sub_cont">${title}</span> T</div></div><div class="item"><div>时间:</div><div><span class="sub_cont">${currYM}${num}</span></div></div><div class="item"><div>状态:</div><div><span class="sub_cont" style="${title >= up ? 'color:#ff3839' : (title <= lower ? 'color:#ff9202' : '')}">${title >= up ? '超过上限' : (title <= lower ? '小于下限' : '正常')}</span></div></div></div> `;// tipsPerDay = layer.tips('默认向右', this);var node = `#tdPerDay${customerId}${num} `;// console.log($(`#tdPerDay${ title }${ num } `));tipsPerDay = layer.tips(html, node, { tips: [3, '#fff', 'width: fit-content;', 'box-shadow: 0px 0px 6px 1px rgba(0,0,0,0.1);'], time: 0 });//}function closeTipsPerDay () {//关闭显示的信息// console.log('关闭显示的信息');layer.close(tipsPerDay);}// hoverPerCompvar tipsPerComp;function showComp (customerName, customerId, invLimit, invUp, invLow, invDaily) {// console.log(customerName, customerId, invLimit, invUp, invLow, invDaily);// console.log('显示的信息');var currYM = new Date().toLocaleDateString().split('/')[0] + '-' + new Date().toLocaleDateString().split('/')[1] + '-';//'2023/8/2'var html = `<div class="hoverDIV_PerDay"><div class="compName">${customerName}</div><div class="item"><div>库存容量:</div><div><span class="sub_cont">${invLimit}</span> T</div></div><div class="item"><div>库存上限:</div><div><span class="sub_cont">${invUp}</span> T</div></div><div class="item"><div>库存下限:</div><div><span class="sub_cont">${invLow}</span> T</div></div><div class="item"><div>每日平均消耗(估):</div><div><span class="sub_cont">${invDaily}</span> T</div></div></div> `;// tipsPerComp = layer.tips('默认向右', this);var node = `#tdPerDay${customerId} `;// console.log($(`#tdPerDay${ title }${ num }`));tipsPerComp = layer.tips(html, node, { tips: [3, '#fff', 'width: fit-content;', 'box-shadow: 0px 0px 6px 1px rgba(0,0,0,0.1);'], time: 0 });//}function closeTipsComp () {//关闭显示的信息// console.log('关闭显示的信息');layer.close(tipsPerComp);}layui.use(['table', 'form'],function () {var table = layui.table;var form = layui.form;form.on('submit(search)', function (data) {// console.log($('#currMonth').val());//2023-02 // 重新获取表头queryYear = $('#currMonth').val().split('-')[0]; //默认获取当前年;//需要查询的年份queryMonth = $('#currMonth').val().split('-')[1]; //默认获取当前月;//需要查询的月份getCurrMonthDays(queryYear, queryMonth);// console.log(cols, daysList);table.reload('test', {cols: [cols],where: {"data": encodeURI(JSON.stringify(data.field).replaceAll("\"", "\\\""))},page: {curr: 1}});return false;});// 获取datalayui.table.render({id: 'test',elem: '#test',title: '入库计划单',height: 'full-80',url: contextPath + '/MngServlet',method: 'post',where: {fn: "customerAction",md: "selectCustomerInvList"},contentType: 'application/json',parseData: function (res) { //res 即为原始返回的数据return {"code": res.rt, //解析接口状态"data": res.data, //解析数据列表"count": res.count,"msg": res.msg};},cols: [cols],done: function (res, curr, count, origin) {this.cols = []; //(关键代码)将cols初始化,否则表格重载时无法正确重新渲染表头// 获取所有表头var totalArr = $('.layui-table-header th');var today = 999;//今日日期totalArr.each(function (index, item) {// console.log(queryYear, queryMonth);//2023 '08'if ((index === 0) || (index === 1)) {return}var currTh = $(this).attr('data-field').split('num')[1];//获取表头的data-field:num28const date = new Date().getDate();//--今日日期:2// var fullDate = new Date().toLocaleDateString();//'2023/8/2' var currYY = new Date().getFullYear(); //默认获取当前年;//需要查询的年份var currMM = checkDate(new Date().getMonth() + 1); //默认获取当前月;//需要查询的月份// 1:比较年if (Number(queryYear) > Number(currYY)) {//如果 未来--全部用绿色$(this).css({ 'background': '#daf6e1', 'color': '#333333', 'border-bottom': '2px solid #00BF39', 'box-sizing': 'border-box' })} else if (Number(queryYear) < Number(currYY)) {//如果 过去--全部用默认$(this).css({ 'background': '#f2f2f2', 'color': '#666', })} else if (Number(queryYear) == Number(currYY)) {// 2:比较月if (Number(queryMonth) > Number(currMM)) {//如果 未来--全部用绿色$(this).css({ 'background': '#daf6e1', 'color': '#333333', 'border-bottom': '2px solid #00BF39', 'box-sizing': 'border-box' })} else if (Number(queryMonth) < Number(currMM)) {//如果 过去--全部用默认$(this).css({ 'background': '#f2f2f2', 'color': '#666', })} else if (Number(queryMonth) == Number(currMM)) {// 3:比较日if (Number(currTh) === Number(date)) {// 相等就是今日today = index;//赋值今日$(this).css({ 'background': '#1e9fff', 'color': '#fff', })} else if (index > today) {// 大于今日就是未来$(this).css({ 'background': '#daf6e1', 'color': '#333333', 'border-bottom': '2px solid #00BF39', 'box-sizing': 'border-box' })} else {$(this).css({ 'background': '#f2f2f2', 'color': '#666', })}}}});}});//监听单元格事件table.on('tool(test)', function (obj) {var data = obj.data;// console.log(data);if (obj.event === 'openCompCharts') {layer.open({title: data.customerName,type: 2,area: ['60%', '80%'],content: './customerCharts.html?customerId=' + data.customerId});}});$(document).on("click", "div[lay-id='test'] .layui-table-body table.layui-table tbody tr", function () {//获取行下标var index = parseInt($(this).parents('tr').prevObject.context.dataset.index);//获取到表对象$(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样$(".layui-table-body tr[data-index=" + index + "]").attr({ "style": "background:#dcdcdc" });//改变当前tr颜色 })//点击复选框取消冒泡(这里默认复选框在table第一列)(只要点在复选框外就会触发行选,取消其他的复选框)$(document).on("click", "tr td:first-child", function (e) {e.stopPropagation();});});</script>
</body></html>
日期控件:限制可选日期(月份):最多到下月
// 默认当月$("#currMonth").val(layui.util.toDateString(get_today(), 'yyyy-MM'));// 设置最大可选月份function maxMonth () {var year = new Date().getFullYear(); //默认获取当前年;//需要查询的年份var month = new Date().getMonth() + 1; //默认获取当前年;//需要查询的年份//获取当前月有多少天var day = new Date(year, month, 0).getDate();if (month == 12) {year = year + 1;month = 0;}// console.log(year + '-' + checkDate(month + 1) + '-' + day);return year + '-' + checkDate(month + 1) + '-' + day;}//执行一个laydate实例layui.laydate.render({elem: '#currMonth',type: 'month',max: maxMonth(),showBottom: false,change: function (value) {timeNoConfirm('currMonth', value);//TODO}});