js实现动态表格

<div>
姓名:<input id="i1" type="text" name="name">
年龄:<input id="i2" type="text" name="age">
性别:<input id="i3" type="radio" name="gender" value="男">男
<input type="radio" name="gender" value="女">女
<button type="button" onclick="add()">添加</button>
</div>

<table id="tb">
<caption>学生信息</caption>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>操作</th>
</tr>
</table>

<script>
/*添加学生*/
function add() {
/*获取姓名*/
let name = document.getElementById("i1").value;
/*获取年龄*/
let age = document.getElementById("i2").value;
/*获取性别*/
let gender = document.getElementById("i3").value;

/*获取table*/
let table = document.getElementById("tb");

table.innerHTML += "<tr>" +
"<td>" + name + "</td>" +
"<td>" + age + "</td>" +
"<td>" + gender + "</td>" +
"<td><a href='javascript:void(0)' onclick='del(this)'>删除</a></td>" +
"</tr>";
}

/*删除学生*/
function del(o) {
/*获取table*/
let table = o.parentElement.parentElement.parentElement;
/*获取tr元素*/
let tr = o.parentElement.parentElement;

/*删除tr,找到table和tr移除就可以了*/
table.removeChild(tr);
}
</script>
上一篇:JavaScript -DOM


下一篇:jQuery取值