我们的目的就是在拿到数据后,通过js把数据渲染到表格的tbody中
html部分
<body>
<table cellspacing="0" border="1" class="table3">
<thead>
<tr>
<th>姓名</th>
<th>科目</th>
<th>成绩</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
js部分
var datas = [
{
name: '小明',
subject: 'JavaScript',
score: 100
},
{
name: '小红',
subject: 'JavaScript',
score: 98
},
{
name: '小刚',
subject: 'JavaScript',
score: 99
},
{
name: '小玉',
subject: 'JavaScript',
score: 96
}
]
var table3 = document.querySelector('.table3')
var tbody3 = table3.children[1]
console.log(tbody3)
for (var i = 0; i < datas.length; i++) {
var tr = document.createElement('tr')
tbody3.appendChild(tr)
for (var k in datas[i]) {
var td = document.createElement('td')
td.innerHTML = datas[i][k]
tr.appendChild(td)
// console.log(datas[i][k])
}
var td = document.createElement('td')
var a = document.createElement('a')
a.href = 'javascript:void(0);'
a.innerHTML = '刪除'
td.appendChild(a)
tr.appendChild(td)
}
for (var i = 0; i < tbody3.children.length; i++) {
var tr = tbody3.children[i]
//console.log(tbody3.children[i])
var removeTd = tr.children[tr.children.length - 1]
//console.log(removeTd.parentNode)
removeTd.onclick = function () {
console.log(this)
// removeTd.parentNode.removeChild(removeTd)
this.parentNode.parentNode.removeChild(this.parentNode)
}
}