日期:2014-05-16 浏览次数:20371 次
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>