页面:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
table {
width: 500px;
margin: 100px auto;
border-collapse: collapse;
text-align: center;
}
td,tr,th{
border: 1px solid #333;
}
thead tr {
height: 40px;
background-color: #ccc;
}
</style>
</head>
<body>
<table cellspacing='0'>
<thead>
<tr>
<th>姓名</th>
<th>课程</th>
<th>分数</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
var datas = [
{
name:'小米',
subject:'js',
score:100,
},
{
name:'小米2',
subject:'js2',
score:102,
},
{
name:'小米3',
subject:'js3',
score:103,
}, {
name:'小米4',
subject:'js4',
score:104,
}
]
//获取数据
var tbody = document.querySelector('tbody')
for (let index = 0; index < datas.length; index++) {
var tr = document.createElement('tr')
tbody.appendChild(tr)
for(var k in datas[index]){
var td = document.createElement('td')
td.innerHTML= datas[index][k]
tr.appendChild(td)
}
//添加单独的删除单元格
var td = document.createElement('td')
td.innerHTML="<a href='javascript:;'>删除</a>"
tr.appendChild(td)
}
//点击删除
var as = document.querySelectorAll('a')
for (let v = 0; v < as.length; v++) {
as[v].onclick =function(){
tbody.removeChild(this.parentNode.parentNode)
}
}
</script>
</body>
</html>