style
.d_f {
display: flex;
}
.flex_1 {
flex: 1;
}
.jc_sb {
justify-content: space-between;
}
.ai_c {
align-items: center;
}
.bc_ccc {
background-color: #cccccc;
}
/* ------------padding------------ */
.bs_bb {
box-sizing: border-box;
}
.p_6 {
padding: 6px;
}
/* - */
.ta_c {
text-align: center;
}
/* ----------- */
.fw_700 {
font-weight: 700;
}
/* ------------------- */
.b_1s_000 {
border: 1px solid #000000;
}
.bl_1s_000 {
border-left: 1px solid #000000;
}
.br_1s_000 {
border-right: 1px solid #000000;
}
.bt_1s_000 {
border-top: 1px solid #000000;
}
.bb_1s_000 {
border-bottom: 1px solid #000000;
}
/* ----------------------- */
.h_68 {
height: 68px;
}
.lh_68 {
line-height: 68px;
}
.h_30 {
height: 30px;
}
.lh_30 {
line-height: 30px;
}
html
<div>
<div>
<h1 class="ta_c">表格1h1>
<div class="b_1s_000">
<div id="idTableHead" class="d_f jc_sb bc_ccc fw_700">div>
<div id="idTableBody">div>
div>
div>
<div>
<h1 class="ta_c">表格2h1>
<div class="b_1s_000">
<div id="idTableHead2" class="d_f jc_sb bc_ccc fw_700">div>
<div id="idTableBody2">div>
div>
div>
div>
JavaScript
(function init() {
// 表格1
createTable([
{
id: 'a1',
title: 'ID'
},
{
id: 'b1',
title: '标题'
},
{
id: 'c1',
title: '昵称'
},
{
id: 'd1',
title: '年龄'
},
{
id: 'e1',
title: '等级'
}
], [
{
id: 'a1',
title: '标题1',
name: '归零',
age: 23,
type: '超级管理员'
},
{
id: 'b1',
title: '标题2',
name: '趴在墙头等红杏',
age: 25,
type: '协管员'
},
{
id: 'c1',
title: '标题3',
name: '零壹',
age: 20,
type: '观察员'
}
], 'idTableHead', 'idTableBody');
// 表格2
createTable([
{
id: 'b1',
title: '标题'
},
{
id: 'c1',
title: '昵称'
},
{
id: 'd1',
title: '年龄'
},
{
id: 'e1',
title: '等级'
}
], [
{
id: 'a1',
title: '标题1',
name: '归零',
age: 23,
type: '超级管理员'
},
{
id: 'b1',
title: '标题2',
name: '趴在墙头等红杏',
age: 25,
type: '协管员'
},
{
id: 'c1',
title: '标题3',
name: '零壹',
age: 20,
type: '观察员'
}
], 'idTableHead2', 'idTableBody2', ['id']);
})();
/**
* 创建表格
* @param {array} tableH 表头
* @param {array} tableH 表内容
* @param {string} idH 表头id
* @param {string} idB 表内容id
* @param {array} arr 不需要渲染的字段
*/
function createTable(tableH, tableB, idH, idB, arr = []) {
let idHEL = document.querySelector(`#${idH}`),
idBEL = document.querySelector(`#${idB}`),
elTableH = '',
elTableB = '';
tableH.forEach((item, i) => {
elTableH += `${i !== 0 ? 'bl_1s_000' : ''}">${item.title}`;
});
idHEL.innerHTML = elTableH;
tableB.forEach(item => {
let elB = '',
i = 0;
for (const key in item) {
if (Object.hasOwnProperty.call(item, key)) {
const val = item[key];
if (!arr.includes(key)) {
elB += `${i !== 0 ? 'bl_1s_000' : ''}">${val}`;
i++;
}
}
}
elTableB += elB + '';
});
idBEL.innerHTML = elTableB;
}
null