动态添加删除表格行的js实现代码
时间:2021-07-01 10:21:17
帮助过:55人阅读
代码如下:
<html>
<head>
<script language="javascript">
//窗口表格增加一行
function addNewRow(){
var tabObj=document.getElementById("myTab");//获取添加数据的表格
var rowsNum = tabObj.rows.length; //获取当前行数
var colsNum=tabObj.rows[rowsNum-1].cells.length;//获取行的列数
var myNewRow = tabObj.insertRow(rowsNum);//插入新行
var newTdObj1=myNewRow.insertCell(0);
newTdObj1.innerHTML="<input type='checkbox' name='chkArr' id='chkArr'"+rowsNum+" style='width:20px' />";
var newTdObj2=myNewRow.insertCell(1);
newTdObj2.innerHTML="<input type='text' name='nodecode' id='nodecode'"+rowsNum+" style='width:40px' value='"+rowsNum+"'/>";
var newTdObj3=myNewRow.insertCell(2);
newTdObj3.innerHTML="<input type='text' name='nodename' id='nodename'"+rowsNum+" style='width:120px' />";
var newTdObj4=myNewRow.insertCell(3);
newTdObj4.innerHTML="<input type='text' name='nodeper' id='nodeper'"+rowsNum+" style='width:60px' />";
}
//窗口表格删除一行
function removeRow(){
var chkObj=document.getElementsByName("chkArr");
var tabObj=document.getElementById("myTab");
for(var k=0;k<chkObj.length;k++){
if(chkObj[k].checked){
tabObj.deleteRow(k+1);
k=-1;
}
}
}
</script>
</head>
<body>
<input type="button" name="xx" onclick="addNewRow();" value="增加一行" />
<input type="button" name="yy" onclick="removeRow();" value="删除一行" />
<table width="600px" border="1" cellpadding="0" cellspacing="0" id="myTab">
<tr>
<td width="40px" class="top-bt liebiao-c" align="center" >操作</td>
<td width="40px" class="top-bt liebiao-c" align="center" >序号</td>
<td class="top-bt liebiao-c" align="center" >节点名称</td>
<td width="80px" class="top-bt liebiao-c" align="center" >节点比例</td>
</tr>
</table>
</body>
</html>