日期:2014-05-16  浏览次数:20442 次

JavaScript操作Table:添加、修改、删除Table元素

方法一:DOM实现

//先获取该表格的引用:
var Container = document.getElementById(TableId);

//然后创建行(TR对象)
var NewTr = document.createElement("tr");

//填充该表格行
var NewTd1 = document.createElement("td");
var NewTd2 = document.createElement("td");
......
NewTr.appendChild(NewTd1);
NewTr.appendChild(NewTd2);
......
下面要做的是继续填充新建好的单元格
另外一种填充表格行的方式是
NewTr.innerHTML = " ........ ";

接下来,要在DOM树中指定NewTr的父节点,

在表格的DOM中,TR的父结点应该是TBODY这个几乎被遗忘的对象.

var LastTr = Container.rows[Container.rows.length - 1];
LastTr.parentNode.appendChild(NewTr);

?

?

通常来讲,从表格中删除某一行一般是通过表格的deleteRow()方法和行的rowIndex属性来删除,如下,欲删除刚刚添加的新行:

var Container = document.getElementById(TableId);
var LastTrIndex = Container.rows.length - 1; // 表格最后一行
Container.deleteRow(LastTrIndex);

?

JavaScript:操作Table(二):使用DOM对象(Table、TableRow、TableCell)

<html>
??? <head>
??? ??? <title>Table Test</title>
??? ???
??? ??? <script type="text/javascript">
??? ??? ??? function $(id) {
??? ??? ??? ??? return document.getElementById(id);
??? ??? ??? }
??? ??? ???
??? ??? ??? function testTable() {
??? ??? ??? ??? var tb1 = $("tb1");//Table对象
??? ??? ??? ??? tb1.createCaption() .innerHTML = "标题";
??? ??? ??? ??? //tb.deleteCaption() ;
??? ??? ??? ??? var tr = tb1.rows ;//TableRow对象数组
??? ??? ??? ??? //alert(tb1.rows.length );//0
??? ??? ??? ??? tb1.insertRow(tb1.rows.length).innerHTML = "<td>行</td>";
??? ??? ??? ??? //alert(tb1.rows.length);//1
??? ??? ??? ??? tb1.insertRow (tb1.rows.length).innerHTML = "<td>行2</td>";
??? ??? ??? ??? //tb1.deleteRow (0);
??? ??? ??? }
??? ??? ???
??? ??? ??? function testTableRow() {
??? ??? ??? ??? var tb1 = $("tb1");//Table对象
??? ??? ??? ??? var tr = tb1.rows;//TableRow对象数组
??? ??? ??? ??? //alert(tr[0].rowIndex );//行号
??? ??? ??? ??? var td = tr[0].cells;//TableCell对象数组
??? ??? ??? ??? //alert(td.length);
??? ??? ??? ??? tr[0].insertCell(0) .innerHTML += " td add"
??? ??? ??? ??? tr[1].insertCell(1).innerHTML += " td add"
??? ??? ??? ??? //tr[1].deleteCell(0) ;
??? ??? ??? }
??? ??? ???
??? ??? ??? function testTableCell() {
??? ??? ??? ??? var tb1 = $("tb1");//Table对象
??? ??? ??? ??? var tr = tb1.rows;//TableRow对象数组
??? ??? ??? ??? var td = tr[0].cells ;//TableCell对象数组
??? ??? ??? ??? alert(td[0].cellIndex );//单元格编号
??? ??? ??? ??? td[1].colSpan = "2";
??? ??? ??? ??? td[0].rowSpan = "2";
??? ??? ??? }
??? ??? ???
??? ??? ??? window.onload = function() {
??? ??? ??? ??? testTable();
??? ??? ??? ??? testTableRow();
??? ??? ??? ??? testTableCell();
??? ??? ??? }
??? ??? </script>??? ???
??? </head>
???
??? <body>
??? ??? <input type="button" value="test" onclick="testTable()"/>
??? ??? <table id="tb1" border="1" background="#fff">
??? ??? ???
??? ??? </table>
??? </body>
</html>