<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test Document</title>
</head>
<body>
<input type="button" value="添加" onclick="addRow('tab')"/>
<table width="350" height="36" border="1" id="tab">
<tr>
<th width="64" height="30" scope="col">姓名</th>
<th width="204" scope="col">地址</th>
<th width="60" scope="col">操作</th>
</tr>
</table>
</body>
</html>
<script type="text/JavaScript">
//取得指定id的对象
function getObj(id){
return document.getElementById(id);
}
//添加行函数
function addRow(tabName){
//取得table的对象
var tab=getObj(tabName);
//添加行
var row=tab.insertRow(tab.rows.length);
//添加三列
var nameCell=row.insertCell(row.cells.length);
var addressCell=row.insertCell(row.cells.length);
var buttonCell=row.insertCell(row.cells.length);
//给name输入栏和address输入栏赋值
nameCell.innerHTML="张三";
addressCell.innerHTML="北京";
//在第三列加上删除当前列按钮
buttonCell.innerHTML='<input value="删除"type="button"onclick="deleteRow(this)"/>';
}
//删除列函数,删除方法传入参数为行的索引
function deleteRow(obj){
var row=obj.parentNode.parentNode;
var tab=row.parentNode;
tab.deleteRow(row.rowIndex);
}
</script>JS 动态添加、删除表格的行
最新推荐文章于 2022-08-22 08:33:46 发布
本文介绍了一种使用JavaScript实现HTML表格行的动态添加和删除的方法。通过简单的按钮操作即可完成表格内容的增删,适用于需要频繁更新表格数据的应用场景。
169

被折叠的 条评论
为什么被折叠?



