使用Javascript动态增加,删除表格

本文介绍了一种使用JavaScript在HTML页面中动态创建和删除表格行的方法。通过两个按钮即可轻松实现表格行的增加和移除,适用于需要灵活管理表格数据的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<html>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<head>

<script language="javascript">
  
function deleteRow(index){
    
var tableObj=document.getElementById("mytable");
    tableObj.deleteRow(tableObj.rows.length
-1);
  }

  
function addRow(){
     
var tableObj=document.getElementById("mytable");
     
var newRowObj=tableObj.insertRow(tableObj.rows.length);
     
var newColName=newRowObj.insertCell(newRowObj.cells.length);
     
var newColAge=newRowObj.insertCell(newRowObj.cells.length);
     
var newColButton=newRowObj.insertCell(newRowObj.cells.length);
     
     newColName.innerHTML
=document.getElementById("newName").value;
     newColAge.innerHTML
=document.getElementById("newAge").value;
     newColButton.innerHTML
='<input type="button" value="删除" onclick="deleteRow();">'
  }

</script>
</head>

<body>
<table width="100%" id="mytable" border="0" cellspacing="0" cellpadding="0">
  
<tr>
    
<td>姓名</td>
    
<td>年龄</td>
    
<td>操作</td>
  
</tr>
  
</table>

<input type="text" name="name" id="newName" />
<input type="text" name="age" id="newAge"/>
<input type="button" onclick="addRow();"  value="新增"/>
</body>
</html> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值