<!DOCTYPE html>
<html>
<head>
<title></title>
<mata http-equiv=”content-type” content=”text/html; charset=gb2312” />
<style type="text/css">
#table1 {
margin: 0 auto;
border: 1px solid gray;
}
#table1 td {
border: 1px solid gray;
height: 60px;
width: 120px;
text-align: center;
line-height: 60px;
}
#table1 tr:hover {
background: #efe5e5;
}
#table1 .delete:hover {
background: #ff6a00;
}
#input {
height: 100px;
width: 200px;
margin: 20px auto;
font-size: 50px;
display: block;
}
p {
width: 250px;
margin: 0 auto;
display: none;
}
</style>
</head>
<body>
<table id="table1">
<tr>
<td>姓名</td>
<td>年纪</td>
<td>性别</td>
<td>操作</td>
</tr>
<tr>
<td>A</td>
<td>21</td>
<td>男</td>
<td><a href="#">删除</a></td>
</tr>
<tr>
<td>B</td>
<td>11</td>
<td>女</td>
<td><a href="#">删除</a></td>
</tr>
<tr>
<td>C</td>
<td>23</td>
<td>男</td>
<td><a href="#">删除</a></td>
</tr>
</table>
<input id="input" type="button" name="name" value="添加" />
<p>
<p>姓名:<input id="name" type="text" placeholder="请输入姓名" /></p>
<p>年龄:<input id="age" type="text" placeholder="请输入年龄" /></p>
<p>性别:<input id="gender" type="text" placeholder="请输入性别" /></p>
<p><input id="add" type="button" value="添加" /></p>
</p>
</body>
</html>
<script>
//取出所有的A标签
var aTags = document.getElementsByTagName('a');
//给取出的A绑定点击事件
deleteTr(aTags);
var input = document.getElementById('input');
input.onclick = function () {
var p = document.getElementsByTagName('p');
p[0].style.display = "block";
}
var add = document.getElementById('add');
add.onclick = function () {
var name = document.getElementById('name').value;
var age = document.getElementById('age').value;
var gender = document.getElementById('gender').value;
var tr = document.createElement('tr');
var html = "<td>" + name + "</td><td>" + age + "</td><td>" + gender + "</td><td><a href=\"#\">删除</a></td>";
tr.innerHTML = html;
var p = document.getElementsByTagName('p');
p[0].style.display = "none";
var table1 = document.getElementById('table1');
table1.appendChild(tr)
;
var allTr = table1.getElementsByTagName('tr');
console.log(allTr.length)
console.log(table1);//为什么取出开的table1里面有2个子元素,我想要的是一个子元素,tr标签包含到table标签里面
//if (tr.length > 6) {
//}
deleteTr(aTags);
}
function deleteTr(tag) {
for (var i = 0; i < aTags.length; i++) {
tag[i].onclick = function () {
//判断是否确定要删除
if (confirm('确定要删除我?')) {
this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);
}
}
}
}
</script>
It will automatically render the upper layer of tbody tag between tr and table. You will know it if you look at F12
You may not understand the level of dom. tr is not a sub-element of table. The above modified answer can easily achieve the function you want. Please refer to it