使用javascript动态添加和删除table的行和列

第一种方法:使用insertRow添加行,使用insertCell添加单元格,再用innerHTML填充单元格。使用deleteRow删除行,代码如下:
Javascript代码:
function addRow()
{
var root = document.getElementById("tbody")
var allRows = root.getElementsByTagName('tr');
var allCells = allRows[0].getElementsByTagName('td');
var newRow = root.insertRow();
var newCell0 = newRow.insertCell();
var newCell1 = newRow.insertCell();
var newCell2 = newRow.insertCell();
var newCell3 = newRow.insertCell();
newCell0.innerHTML = allCells[0].innerHTML;
newCell1.innerHTML = allCells[1].innerHTML;
newCell2.innerHTML = allCells[2].innerHTML;
newCell3.innerHTML = allCells[3].innerHTML;

}
function removeRow(r)
{
var root = r.parentNode;
root.deleteRow(r);
}
HTML代码:


<table>
<tbody id="tbody">
<tr>
<td><select><option>hello</option><option>hi</option></select></td>
<td><input type="text" value="enter you name here" /></td>
<td><input type="text" value="text2"/></td>
<td><input type="button" value="remove" οnclick="removeRow(this.parentNode.parentNode)"/></td>
</tr>
</tbody>
</table>
<table><tr><td><input type="button" value="add" οnclick="addRow()" /></td></tr></table>
第二种方法:使用cloneNode方法(复制节点)和appendChild(附加子元素),使用removeChild删除子元素,代码如下:

Javascript代码: function addRow()
{
var root = document.getElementById("tbody");
var allRows = root.getElementsByTagName('tr');
var cRow = allRows[0].cloneNode(true)
root.appendChild(cRow);
}
function removeRow(r)
{
var root = r.parentNode;
var allRows = root.getElementsByTagName('tr')
if(allRows.length>1)
root.removeChild(r);
else
alert("only one row left, you not need to remove it.");
}
HTML代码:
<table border="0" cellspacing="0" cellpadding="0">
<tbody id="tbody">
<tr>
<td><input type="text" name="text1" /></td>
<td><input type="text" name="text2" /></td>
<td><select name="select">
<option>item1</option>
<option>item2</option>
<option>item3</option>
<option>item4</option>
<option>item5</option>
</select></td>
<td><input type="button" value="Remove" οnclick="removeRow(this.parentNode.parentNode)"></td>
</tr></tbody>
</table>
<input name="button" type="button" value="Add row" οnclick="addRow(')">

以上代码IE7.0测试通过。其他浏览器未检测。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值