javascript动态添加与删除表格行
程序员文章站
2022-04-25 07:51:52
...
代码:
<html>
<head>
<meta charset="utf-8">
<title>增加删除元素</title>
</head>
<body>
学号:<input type="text" id="id"/>
姓名:<input type="text" id="name"/>
年龄:<input type="text" id="age"/>
<div>
<button onclick="addRow()">添加</button>
<button onclick="removeLastRow()">删除</button>
</div>
<hr />
<table id='stu' align="center" width="300" cellpadding="5" border="1">
<caption>
<font size="5">学生基本信息表</font>
</caption>
<tr>
<th>学号</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</table>
<p id='recno'>记录数:0</p>
<script>
var no=0;
function addRow(){
no++;
var tab = document.getElementById("stu");
var id=document.getElementById("id").value;
var name=document.getElementById("name").value;
var age = document.getElementById("age").value;
var r = tab.insertRow();
r.attributes.id=no;
var c1 = r.insertCell(0);
var c2 = r.insertCell(1);
var c3 =r.insertCell(2);
c1.innerHTML=id;
c2.innerHTML=name;
c3.innerHTML=age;
var rscno = document.getElementById('recno');
recno.innerText='记录数:'+(tab.rows.length-1);
}
function removeLastRow(){
if(no==0){
alert('没有记录可删');
return;
}
var tab = document.getElementById('stu');
tab.deleteRow(no);
no--;
var recno=document.getElementById('recno');
recno.innerText='记录数'+(tab.rows.length-1);
}
</script>
</body>
</html>
效果图:
上一篇: 商城左侧菜单栏网页模板
下一篇: JavaScript——对象