运行展示:
可以实现学生成绩的增加删除功能。
代码部分:
<!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>
</head>
<style>
a {
text-decoration: none;
}
table {
width: 500px;
margin: 100px auto;
border-collapse: collapse;
text-align: center;
}
td,
th {
border: 1px solid #333;
}
thead tr {
height: 40px;
background-color: #ccc;
}
div{
margin: 100px;
}
</style>
</head>
<body>
<table cellspacing="0">
<thead>
<tr>
<th>姓名</th>
<th>科目</th>
<th>成绩</th>
<th>操作</th>
</tr>
</thead>
<tbody></tbody>
</table>
<div>
<input type="text" id="name" placeholder="请输入姓名"></br>
<input type="text" id="subject" placeholder="请输入科目"></br>
<input type="text" id="score" placeholder="请输入成绩"></br>
<input type="button" value="添加" id="btn_add">
</div>
<script>
var datas = [
{
name: '张三',
subject: 'JavaScript',
score: 100
},
{
name: '李四',
subject: 'JavaScript',
score: 98
},
{
name: '刘五',
subject: 'JavaScript',
score: 99
},
];
var tbody = document.querySelector('tbody');
for (var i = 0; i < datas.length; i++) {
var tr = document.createElement('tr');
tbody.appendChild(tr);
for (var k in datas[i]) {
var td = document.createElement('td');
td.innerHTML = datas[i][k];
tr.appendChild(td);
}
var td = document.createElement('td');
td.innerHTML = '<a href="javascript:void(0);"onclick="deleteTr(this);" >删除</a>'
tr.appendChild(td);
}
function deleteTr(object) {
var table = object.parentNode.parentNode.parentNode;
var tr = object.parentNode.parentNode;
table.removeChild(tr);
}
document.getElementById("btn_add").onclick = function() {
var name = document.getElementById("name").value;
var subject = document.getElementById("subject").value;
var score = document.getElementById("score").value;
var table = document.getElementsByTagName("table")[0];
table.innerHTML += "<tr>\n" +
" <td>"+name+"</td>\n" +
" <td>"+subject+"</td>\n" +
" <td>"+score+"</td>\n" +
" <td><a href=\"javascript:void(0);\" onclick=\"delTr(this);\" >删除</a></td>\n" +
" </tr>";
};
</script>
</body>
</html>