<body>
<table border="1px">
<thead>
<tr>
<td>姓名</td>
<td>科目</td>
<td>成绩</td>
<td>操作</td>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
let data=[
{uname:'小李',subject:'js',score:'100'},
{uname:'哈哈',subject:'js',score:'90'},
{uname:'小红',subject:'js',score:'80'},
{uname:'小张',subject:'js',score:'90'},
{uname:'小杨',subject:'js',score:'50'},
{uname:'小乔',subject:'js',score:'100'}
]
let tbody = document.querySelector('tbody')
for(let i = 0;i<data.length;i++){
let tr =document.createElement('tr')
tbody.appendChild(tr)
for(let k in data[i]){
let td = document.createElement('td')
tr.appendChild(td)
td.innerHTML = data[i][k]
}
}
let tr = tbody.querySelectorAll('tr')
for(let i= 0;i<data.length;i++){
let td = document.createElement('td')
tr[i].appendChild(td)
td.innerHTML = `<span>删除</span>`
let span = document.querySelectorAll('span')
span[i].onclick = function(){
tbody.removeChild(this.parentNode.parentNode)
}
}
</script>
</body>
先声明数组,里面存放上数据,根据数组的长度来进行遍历动态在tbody里面添加tr,然后遍历对象,动态创建td,利用innerHTML将内容写入到td中。后面的删除,首先先获得tbody里面的tr,根据数组长度创建td,td.innerHTML = `<span>删除</span>`,td里面的内容就会是删除,如何点击删除tr呢?需要获得span标签,通过tbody.removeChild来进行删除