<!--动态表格添加-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>动态表格</title>
<style type="text/css">
table{
border: 1px solid;
margin: auto;
width: 500px;
}
td,th{
text-align: center;
border: 1px solid;
}
div{
text-align: center;
margin: 50px;
}
</style>
</head>
<body>
<div>
<input type="text" id="id" placeholder="请输入编号">
<input type="text" id="name" placeholder="请输入姓名">
<input type="text" id="gender" placeholder="请输入性别">
<input type="button" value="添加" id="btn_add">
</div>
<table>
<caption>学生信息表</caption>
<tr>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>操作</th>
</tr>
<tr>
<td>1</td>
<td>令狐冲</td>
<td>男</td>
<td><a href="javascript:void(0);" onclick="delTr(this)">删除</a></td>
</tr>
<tr>
<td>2</td>
<td>任我行</td>
<td>男</td>
<td><a href="javascript:void(0);" onclick="delTr(this)">删除</a></td>
</tr>
<tr>
<td>3</td>
<td>岳不群</td>
<td>?</td>
<td><a href="javascript:void(0);" onclick="delTr(this)">删除</a></td>
</tr>
</table>
<script type="text/javascript">
/*
分析:
1.添加
1.给添加按钮绑定单击事件
2.获取文本框的内容
3.创建td,设置td的文本为文本框的内容。
4.创建tr
5.将td添加到tr中
6.获取table,将tr添加到table中
2.删除:
1.确定点击的是哪一个超链接
<a href="javascript:void(0);" onclick="delTr(this)">删除</a>
2.怎么删除?
removeChild():通过父节点删除子节点
*/
//1.获取按钮
document.getElementById("btn_add").onclick = function(){
// 2.获取文本框的内容
var id = document.getElementById("id").value;
var name = document.getElementById("name").value;
var gender = document.getElementById("gender").value;
//3.创建td,赋值td的标签体
//id 的 td
var td_id = document.createElement("td");
var text_id = document.createTextNode(id);
td_id.appenChild(text_id);
//name 的 td
var td_name = document.createElement("td");
var text_name = document.createTextNode(name);
td_name.appenChild(text_name);
//gender 的 td
var td_gender = document.createElement("td");
var text_gender = document.createTextNode(gender);
td_gender.appenChild(text_gender);
//a标签的td
var td_a = document.createElement("td");
var ele_a = document.createElement("a");
//javascript:void(0)
ele_a.setAttribute("href","javascript:void(0);");
ele_a.setAttribute("onclick","delTr(this);");
var text_a = document.createTextNode("删除");
ele_a.appenChild(text_a);
td_a.appenChild(ele_a);
//4.创建tr
var tr = document.createElement("tr");
//5.添加td到tr中
tr.appenChild(td_id);
tr.appenChild(td_name);
tr.appenChild(td_gender);
tr.appenChild(td_a);
//6.获取table
var table = document.getElementByTagName("table")[0];
table.appenChild(tr);
}
//删除方法
function delTr(obj){
//alert(obj);
var table = obj.parentNode.parentNode.parentNode;
var tr = obj.parentNode.parentNode;
table.removeChild(tr);
}
</script>
</body>
</html>
05-02
4783
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)