1.效果图
2.代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#div1 {
width: 500px;
margin: 20px 20px;
}
#stu {
width: 500px;
margin-left: 20px;
border-collapse: collapse;
}
#stu th, td {
border: 1px solid #CCCCCC;
text-align: center;
}
</style>
<script>
window.onload = function () {
var oBtn = document.getElementById('submit');
var oTable = document.getElementById('stu');
var aTrs = oTable.getElementsByTagName('tr');
var id = 0;
oBtn.onclick = function () {
var oName = document.getElementById('name');
var oAge = document.getElementById('age');
var oTbody = oTable.tBodies[0];
id++;
var oTr = document.createElement('tr');
var oTdId = document.createElement('td');
var oTdName = document.createElement('td');
var oTdAage = document.createElement('td');
var oTdOpe = document.createElement('td');
oTdId.innerHTML = id;
oTdName.innerHTML = oName.value;
oTdAage.innerHTML = oAge.value;
oTdOpe.innerHTML = '<a href="javascript:">删除</a>';
oTdOpe.getElementsByTagName('a')[0].onclick = function () {
oTbody.removeChild(this.parentNode.parentNode);
};
oTr.appendChild(oTdId);
oTr.appendChild(oTdName);
oTr.appendChild(oTdAage);
oTr.appendChild(oTdOpe);
oTbody.appendChild(oTr);
};
};
</script>
</head>
<body>
<div id="div1">
姓名:<input type="text" id="name">
年龄: <input type="text" id="age">
<input type="button" id="submit" value="添加">
</div>
<table id="stu">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>