Table 对象
Table 对象代表一个 HTML 表格。
在 HTML 文档中 <table> 标签每出现一次,一个 Table 对象就会被创建。
Table 对象集合
table对象 常用集合
1. Table cells 集合
cells 集合返回表格中所有 <td> 或 <th> 元素。
tableObject.cells
.length 返回集合中 <td> 或 <th> 元素的数目。
2. Table rows 集合
rows 集合返回表格中所有行(TableRow 对象)的一个数组,即一个 HTMLCollection。
该集合包括 <thead>、<tfoot> 和 <tbody> 中定义的所有行
tableObject.rows
.length 返回集合中 <tr>元素的数目。
Table 对象方法
table对象常用方法:
1.insertRow() 方法用于在表格中的指定位置插入一个新行。
tableObject.insertRow(index) //index 指定插入新行的位置 (以 0 开始)。
2. deleteRow() 方法用于从表格删除指定位置的行
tableObject.deleteRow(index) //index 指定插入新行的位置 (以 0 开始)。
例子1:下面的例子使用 cells 来显示出第1行第1个单元格的长度:
<html> <head> <script> function displayResult() { alert(document.getElementById("myTable").rows[0].cells.length); } </script> </head> <body> <table id="myTable" border="1"> <tr> <td>cell 1</td> <td>cell 2</td> </tr> <tr> <td>cell 3</td> <td>cell 4</td> </tr> </table> <br> <button type="button" onclick="displayResult()">Show number of cells</button> </body> </html>
例子2:显示表格中行的数目
<html> <head> <script> function displayResult() { alert(document.getElementById("myTable").rows.length); } </script> </head> <body> <table id="myTable" border="1"> <tr> <td>cell 1</td> <td>cell 2</td> </tr> <tr> <td>cell 3</td> <td>cell 4</td> </tr> </table> <br> <button type="button" onclick="displayResult()">Show number of rows in table</button> </body> </html>
例子3:在表格的第一位置插入一个新行:
<!DOCTYPE html> <html> <head> <script> function displayResult() { var table=document.getElementById("myTable"); var row=table.insertRow(0); var cell1=row.insertCell(0); var cell2=row.insertCell(1); cell1.innerHTML="New"; cell2.innerHTML="New"; } </script> </head> <body> <table id="myTable" border="1"> <tr> <td>cell 1</td> <td>cell 2</td> </tr> <tr> <td>cell 3</td> <td>cell 4</td> </tr> </table> <br> <button type="button" onclick="displayResult()">Insert new row</button> </body> </html>
例子4:删除表格的第一行:
<html>
<head>
<script>
function displayResult()
{
document.getElementById("myTable").deleteRow(0);
}
</script>
</head>
<body>
<table id="myTable" border="1">
<tr>
<td>cell 1</td>
<td>cell 2</td>
</tr>
<tr>
<td>cell 3</td>
<td>cell 4</td>
</tr>
</table>
<br>
<button type="button" onclick="displayResult()">Delete first row</button>
</body>
</html>
例子5:删除当前行
<html>
<head>
<script>
function deleteRow(r)
{
var i=r.parentNode.parentNode.rowIndex;
document.getElementById('myTable').deleteRow(i);
}
</script>
</head>
<body>
<table id="myTable" border="1">
<tr>
<td>Row 1</td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
</tr>
<tr>
<td>Row 2</td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
</tr>
<tr>
<td>Row 3</td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
</tr>
</table>
</body>
</html>