小白第一次打卡
简单模拟了一下动态表格;
功能:新增和删除数据时重新遍历一遍序号,保证正确的序号;
但此代码没有对新增的内容限制,就算新增空白也能添加。
<html>
<head>
<title>动态表格by-夜梦昔</title>
<style type="text/css">
div{
padding:5px 10px;
text-align:center;
}
table{
margin:10px auto;
text-align:center;
}
</style>
<script type="text/javascript">
//增加
function add(){
var num =document.all.num.value;
var name =document.all.name.value;
var sex =document.all.sex.value;
var html ="<tr>";
html += "<td name='num'>"+num+"</td>";
html += "<td>"+name+"</td>";
html += "<td>"+sex+"</td>";
html += "<td>"+"<a href='#' onclick='del(this)'>"+"删除"+"</a>"+"</td>";
html += "</tr>";
var table = document.getElementById("tab");
table.innerHTML += html;
change();
}
function change(){
var number =document.getElementsByName("num");
for(i=0;i<number.length;i++){
number[i].innerHTML=i;
}
}
//删除
function del(obj){
var tr = obj.parentNode.parentNode;
var table = obj.parentNode.parentNode.parentNode;
table.removeChild(tr);//删除table的tr
change();
}
</script>
</head>
<body>
<div width="45%" align="center">
<input type="num" name="num" placeholder="请输入编号">
<input type="text" name="name" placeholder="请输入姓名">
<input type="sex" name="sex"placeholder="请输入性别">
<input type="button" onclick="add()" value="添加">
</div>
<table border="1" id="tab" align="center" width="45%">
<tr>
<td>编号</td>
<td>姓名</td>
<td>性别</td>
<td>操作</td>
</tr>
<tr>
<td name="num">1</td>
<td>张三</td>
<td>男</td>
<td><a href="#" onclick="del(this)">删除</a></td>
</tr>
<tr>
<td name="num">2</td>
<td>李四</td>
<td>女</td>
<td><a href="#" onclick="del(this)">删除</a></td>
</tr>
<tr>
<td name="num">3</td>
<td>王五</td>
<td>男</td>
<td><a href="#" onclick="del(this)">删除</a></td>
</tr>
</table>
</body>
</html>