複製鏈接
請複製以下鏈接發送給好友

insertCell()

鎖定
insertCell() 方法用於在 HTML 表的一行的指定位置插入一個空的 元素。
中文名
insertCell()
拋    出
參數 index 小於 0
語    法
index

目錄

  1. 1 簡介
  2. 語法
  3. 説明
  1. 拋出
  2. 2 實例
  3. 實例一
  1. 實例二

insertCell()簡介

insertCell()語法

tablerowObject.insertCell(index)返回值

insertCell()説明

該方法將創建一個新的 <td> 元素,把它插入行中指定的位置。新單元格將被插入當前位於 index 指定位置的表元之前。如果 index 等於行中的單元格數,則新單元格被附加在行的末尾。
請注意,該方法只能插入 <td> 數據表元。若需要給行添加頭表元,必須用 Document.createElement() 方法和 Node.insertBefore() 方法(或相關的方法)創建並插入一個 <th> 元素

insertCell()拋出

若參數 index 小於 0 或大於等於行中的的表元數,該方法將拋出代碼為 INDEX_SIZE_ERR 的 DOMException 異常。

insertCell()實例

insertCell()實例一

下面的例子在表格行中插入了一個單元格
<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> [1] 

insertCell()實例二

表格中插入一個新列。
<table id=“mytable” width=“80%” border=“1” cellpadding=“0” cellspacing=“0” bordercolor=“blue”>
<tr><td>1</td><td>2</td></tr>
<tr><td>3</td><td>4</td></tr>
</table>
<button onclick=“InsertCol()">插入列</button>
<script type=“text/javascript”>
function InsertCol()
{
var n = document.getElementById(“mytable”)。rows.length;
for( i=0; i<n; i++ )
{
x = document.getElementById(“mytable”)。rows[i].insertCell(0);
x.innerHTML = “&nbsp;”;
}
}
</script>
説明:rows[]是表格所有行組成的數組,rows.length代表了表格的行數,利用循環在表格每行的開始處插入單元格,innerHTML屬性為單元格設置內容。
注:如果沒有合併單元格,應保證表格每行中的單元格數量相同,否則生成的表格會變形。 [2] 
參考資料