说在前面:
最近一直在用layui处理表格
写的有些代码感觉还挺有用的,顺便记录下来方便以后查看使用;
HTML处代码
拿到id 渲染位置表格
<div class="layui-table-body salaryTable"><table class="layui-table" id="ID-table-salary-parse" style="display:block"></table></div>
CSS
.layui-table th {background-color: rgb(199 217 234 / 78%); /* 设置表头的背景颜色 */color: #2e2e2e; /* 设置表头的文本颜色 */font-weight: bold;}.layui-table tbody tr:nth-child(odd) {background-color: #ffffff; /* 设置奇数行的背景颜色 */}.layui-table tbody tr:nth-child(even) {background-color: rgba(239, 239, 239, 0.94); /* 设置偶数行的背景颜色 */}.layui-table td, .layui-table th {border: 1px solid #e6e6e6; /* 边框颜色 */}.layui-table td, .layui-table th {border-width: 2px; /* 设置双边框效果 */}
重点来了
JS代码
var backData = {};
var backData3 = {};
layui.use('table', function () {getStudentTaskData()function getStudentTaskData() {ajaxBase.getSelectInfo(false, function (jsonData) {if (jsonData['单据json']) {backData = jsonData['代扣项目'];backData3 = jsonData['工资薪酬计算表'];}})}var datas = []$.each(backData3, function (index, item) {var coll = {};for (key in item) {coll[key.split("、")[1]] = item[key];}datas.push(coll);})var table = layui.table;var colLists = [];for (key in backData[0]) {var colList = {};colList['field'] = key;colList['title'] = key;colList['align'] = 'center';colList['minWidth'] = '122';colLists.push(colList);}colLists.sort();// 渲染table.render({elem: '#ID-table-demo-parse', data: backData, cols: [colLists], height: 100});colLists = [];var colls = [];const site = 0;var colList = {};for (key in backData3[0]) {colList[key.split("、")[0]] = key.split("、")[1]}for (key in colList) {var coll = {};if (colList[key].includes('代扣项目')) {coll['field'] = colList[key];coll['edit'] = 'text';coll['title'] = colList[key].split("-")[1];coll['align'] = 'center';colls.push(coll);// colLists.push(coll);} else {coll['field'] = colList[key];coll['title'] = colList[key];coll['edit'] = 'text';coll['rowspan'] = 2;coll['align'] = 'center';colLists.push(coll);if (colList[key].includes('收入总额')) {var colll = {};colll['field'] = '代扣项目';colll['title'] = '代扣项目';colll['align'] = 'center';colll['colspan'] = 5;colLists.push(colll);}}}//console.log('colLists', colLists)// 渲染table.render({elem: '#ID-table-salary-parse', data: datas, cols: [colLists, colls], height: 350});
});
合并表头需要在
cols中传入[ [ ],[ ] ]这种数组类型的格式;
主要就是不合并的表头都加上rowspan:2(代表行跨度为2)
colspan:5 表示第二个数组需要合并的表格个数;
完成效果图:
小程序演示地址:
点击演示