<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="http://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.js"></script>
<!-- <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>-->
<script type="text/javascript" src="http://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
</head>
<body>
<div id="app">
</div>
</body>
<script>
$('#app').html('<table class="display" id="example"></table>');//动态生成表格
$(document).ready(function () {
//这里用异步请求后端,获取数据
let dataset = [
{id: 0, name: 'alice', age: 2, money: 2},
{id: 2, name: 'vilson', age: 5, money: 2}
];//数据格式
let colunms = [
{
"title": '序号',
"class": "center",
"render": function (data, type, full, meta) {
return meta.row + 1;
}
}
];
//将要渲染的colunms
//根据后端返回的数据,取第一条数据,拼装colunms
$.each(dataset[0], function (key, val) {
let obj = {
"title": key,
"class": "center",
"render": function (data, type, full, meta) {
return full[key];
}
};
colunms.push(obj);
});
$('#example').DataTable({
"processing": true, //是否显示处理状态(排序的时候,数据很多耗费时间长的话,也会显示这个)
"data": dataset,//设置数据
"columns": colunms
});
});
</script>
<style>
.center {
text-align: center;
}
</style>
</html>