標籤:
html建立表格:
<table berder=‘1‘ width=‘300‘> <thead> <tr> <th>姓名</th> <th>性別</th> <th>年齡</th> </tr> </thead> <tbody> <tr> <th>tzr</th> <th>男</th> <th>24</th> </tr> </tr> </tbody> <tfoot> <tr> <th>結束</th> </tr> </tfoot> </table>
而利用DOM建立方法為:
window.onload=function(){ var table=document.createElement(‘table‘); table.width=300; table.border=1;}
利用appendChild()方法添加表格的thead、tr,th。如:
var thead=document.createElement(‘thead‘);table.appendChild(thead);
可以看出,使用DOM建立表格比較累。
下面看看如何使用DOM擷取表格式資料:擷取table第一個子節點caption的內容。
window.onload=function(){ var table=document.getElementByTagName(‘table‘)[0]; alert(table.children[0].innerHTML);}
所以,我們常使用HTML DOM。
table.caption.innerHTML;
table.caption.innerHTML=‘人員表‘;
table.thead;
table.tfoot;
table.tBodies; //返回tbody集合
table.rows; //所有tr集合
table.tBodies[0].rows; //主體tbody的tr集合
table.tBodies[0].rows[1].cells[1].innerHTML; //返回主體第二行第二個儲存格的內容
table.deleteCaption();
table.deleteTHead();
table.tBodies[0].deleteRow(0); //刪除主體第一行
table.tBodies[0].rows[1].deleteCell(1); //刪除主體第二行第二個資料
最後,我們可以簡單快捷地建立一個表格。
table.createCaption().innerHTML=‘人員表‘;
var thead=table.createTHead();
var tr=thead.insertRow(0);
tr.insertCell(0).innerHTML=‘資料1‘;
tr.insertCell(1).innerHTML=‘資料2‘;
tr.insertCell(2).innerHTML=‘資料3‘;
PS:在建立表格時,<table>,<tbody>,<th>沒有特定的方法。
DOM動作表格——HTML DOM