代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>htmldom的增删改查</title>
<script type="text/javascript">
window.οnlοad=function()
{
document.getElementById("btn1").onclick = function(){
var tab = document.getElementById("tab");
var rowlength = tab.rows.length;//得到表格的行数,rows是一个数组
//alert("rowlength:"+rowlength);
var newRow = tab.insertRow(rowlength);//在末尾增加一行,返回行对象
//为一行添加格子,
var td1 = newRow.insertCell(0);
var td2 = newRow.insertCell(1);
var td3 = newRow.insertCell(2);
var td4 = newRow.insertCell(3);
td1.innerHTML="addtd1";
td2.innerHTML="addtd2";
td3.innerHTML="addtd3";
td4.innerHTML="操作";
}
//删除指定的行
document.getElementById("btn2").onclick = function(){
var tab = document.getElementById("tab");
var rows = tab.rows;
tab.deleteRow(rows.length-1);
}
//删除每个表的最后一个格子
document.getElementById("btn3").onclick = function(){
var tab = document.getElementById("tab");
var rows= tab.rows;
for (var k = 0; k < rows.length; k++) {
var row = rows[k];
var cellslen = row.cells.length;
row.deleteCell(cellslen-1);
}
}
document.getElementById("btn4").onclick = function(){
var tab = document.getElementById("tab");
var rows = tab.rows;
for (var j = 0; j < rows.length;j++)
{
var row = rows[j];
var cellsLen = row.cells.length;
var td = row.insertCell(cellsLen);
td.innerHTML="追加末尾成功添加"
}
}
}
</script>
</head>
<body>
<table border="1" id = "tab">
<tr>
<td>thead1</td>
<td>thead2</td>
<td>thead3</td>
<td>操作</td>
</tr>
<tr>
<td> tbody1</td>
<td> tbody2</td>
<td> tbody3</td>
<td>操作</td>
</tr>
<tr>
<td>tbody4</td>
<td>tbody5</td>
<td>tbody6</td>
<td>操作</td>
</tr>
<tr>
<td>tfoot7</td>
<td>tfoot8</td>
<td>tfoot9</td>
<td>操作</td>
</tr>
</table>
<input id="btn1" type="button" value="末尾增加一行"/>
<input id="btn2" type="button" value="末尾删除一行"/>
<input id="btn3" type="button" value="删除每一行的最后一个cell"/>
<input id="btn4" type="button" value="插入某一行的指定的cell"/>
</body>
</html>