layui下载:http://layui.88662.top/index.html
代码:
js:
function loadTable() {
//默认加载普通表格
//加载固定列加多表头表格
loadTablePage($("#table-guding-duo")[0]);
}
let tableData = undefined;
function getTableData() {
if (tableData == undefined) {
$.ajax({
url: "../data/user.json",
type: "get",
async: false,
success: function (res) {
tableData = res.data;
}
})
}
return tableData;
}
/** 加载具体数据 */
function loadTablePage(box) {
box.innerHTML = "";
let data = tableData;
if (data == undefined) {
data = getTableData();
}
let cols = setTable(box);
let elem = document.createElement("div");
elem.className = "dataTable";
box.appendChild(elem);
layui.use("table",function(){
let table = layui.table;
table.render({
elem:elem,
data:data,
width:500,
height:300,
even: true,
cols:cols,
page:true
})
})
}
/** 设置表 */
function setTable(box) {
let type = parseInt(box.getAttribute("data-type"));
let res = [];
switch (type) {
case 1://普通表格
break;
case 2://固定列
break;
case 3://多表头
break;
case 4://固定列加多表头
res = [
[
{type:"numbers",title:"序号",fixed:"left",align:"center",rowspan:2,width:80},
{field:"",title:"基本信息",colspan:3,align:"center",width:300},
{field:"",title:"其它信息",colspan:2,align:"center",width:200}
],
[
{field:"name",title:"姓名",align:"center",width:100},
{field:"age",title:"年龄",align:"center",width:100},
{field:"sex",title:"性别",align:"center",width:100},
{field:"nickname",title:"昵称",align:"center",width:100},
{field:"hobby",title:"爱好",align:"center",width:100}
]
];
break;
}
return res;
}
html:
<div class="layui-tab layui-tab-card" id="table-card">
<ul class="layui-tab-title">
<li class="">普通表格</li>
<li>固定列</li>
<li>多表头</li>
<li class="layui-this">固定列加多表头</li>
</ul>
<div class="layui-tab-content" id="table-con">
<div class="layui-tab-item " id="table-putong" data-type="1"></div>
<div class="layui-tab-item" id="table-guding" data-type="2"></div>
<div class="layui-tab-item" id="table-duo" data-type="3"></div>
<div class="layui-tab-item layui-show" id="table-guding-duo" data-type="4"></div>
</div>
</div>
user.json
{
"data":[
{"name":"张三","age":20,"sex":"男","nickname":"zs","hobby":"看书"},
{"name":"李四","age":22,"sex":"男","nickname":"ls"},
{"name":"张三","age":20,"sex":"男","nickname":"zs"},
{"name":"李四","age":22,"sex":"男","nickname":"ls"},
{"name":"张三","age":20,"sex":"男","nickname":"zs"},
{"name":"张三","age":20,"sex":"男","nickname":"zs","hobby":"看书"},
{"name":"李四","age":22,"sex":"男","nickname":"ls"},
{"name":"张三","age":20,"sex":"男","nickname":"zs"},
{"name":"李四","age":22,"sex":"男","nickname":"ls"},
{"name":"张三","age":20,"sex":"男","nickname":"zs"},
{"name":"张三","age":20,"sex":"男","nickname":"zs","hobby":"看书"},
{"name":"李四","age":22,"sex":"男","nickname":"ls"},
{"name":"张三","age":20,"sex":"男","nickname":"zs"},
{"name":"李四","age":22,"sex":"男","nickname":"ls"},
{"name":"张三","age":20,"sex":"男","nickname":"zs"}
]
}
效果: