<body>
<div>
<button id="bth_show">显示数据</button>
<table border="1">
<thead>
<tr>
<th width="100">姓名</th>
<th width="100">年龄</th>
<th width="100">地址</th>
</tr>
</thead>
</table>
</div>
<script>
//1、用数组保存数据
let students = [
{
name: '贾宝玉',
age: '20',
address: '江苏镇江',
},
{
name: '林黛玉',
age: '18',
address: '江苏南京',
},
{
name: '王熙凤',
age: '25',
address: '江苏南京',
},
]
// 2、定义函数
let flag = false
function writeTable() {
let tbody = document.querySelector('tbody')
if (flag == false) {
for (let i = 0; i < students.length; i++) {
let tr = document.createElement('tr')
tbody.appendChild(tr)
for (let k in students[i]) {
let td = document.createElement('td')
td.innerHTML = students[i][k]
tr.appendChild(td)
}
}
flag = true
}
}
// 3、给按钮注册事件
document.querySelector('#bth_show').addEventListener('click', writeTable)
</script>
</body>
按钮注册事件