HTML DOM insertCell() 方法
定義和用法
insertCell() 方法用于在 HTML 表的一行的指定位置插入一個(gè)空的 <td> 元素。
語法
tablerowObject.insertCell(index)
返回值
一個(gè) TableCell 對(duì)象,表示新創(chuàng)建并被插入的 <td> 元素。
說明
該方法將創(chuàng)建一個(gè)新的 <td> 元素,把它插入行中指定的位置。新單元格將被插入當(dāng)前位于 index 指定位置的表元之前。如果 index 等于行中的單元格數(shù),則新單元格被附加在行的末尾。
請(qǐng)注意,該方法只能插入 <td> 數(shù)據(jù)表元。若需要給行添加頭表元,必須用 Document.createElement() 方法和 Node.insertBefore() 方法(或相關(guān)的方法)創(chuàng)建并插入一個(gè) <th> 元素。
拋出
若參數(shù) index 小于 0 或大于等于行中的的表元數(shù),該方法將拋出代碼為 INDEX_SIZE_ERR 的 DOMException 異常。
實(shí)例
下面的例子在表格行中插入了一個(gè)單元格:
<html>
<head>
<script type="text/javascript">
function insCell()
{
var x=document.getElementById('tr2').insertCell(0)
x.innerHTML="John"
}
</script>
</head>
<body>
<table border="1">
<tr id="tr1">
<th>Firstname</th>
<th>Lastname</th>
</tr>
<tr id="tr2">
<td>Peter</td>
<td>Griffin</td>
</tr>
</table>
<br />
<input type="button" onclick="insCell()" value="Insert cell">
</body>
</html>