16. 操作表格
为了方便构建表格,HTML DOM 还为 table 、 tbody和 tr 元素添加了一些属性和方法。
为 table 元素添加的属性和方法如下。
| 方法 | 描述 |
|---|---|
| caption | 保存着对 <caption> 元素(如果有)的指针。 |
| tBodies | 是一个 tbody 元素的 HTMLCollection 。 |
| tFoot | 保存着对 tfoot 元素(如果有)的指针。 |
| tHead | 保存着对 thead 元素(如果有)的指针。 |
| rows | 是一个表格中所有行的 HTMLCollection 。 |
| createTHead() | 创建 thead 元素,将其放到表格中,返回引用。 |
| createTFoot() | 创建 tfoot 元素,将其放到表格中,返回引用。 |
| createCaption() | 创建 caption 元素,将其放到表格中,返回引用。 |
| deleteTHead() | 删除 thead元素。 |
| deleteTFoot() | 删除 tfoot 元素。 |
| deleteCaption() | 删除 caption 元素。 |
| deleteRow(pos) | 删除指定位置的行。 |
| insertRow(pos) | 向 rows 集合中的指定位置插入一行。 |
为 tbody 元素添加的属性和方法如下。
| 方法 | 描述 |
|---|---|
| rows | 保存着 tbody 元素中行的 HTMLCollection 。 |
| deleteRow(pos) | 删除指定位置的行。 |
| insertRow(pos) | 向 rows 集合中的指定位置插入一行,返回对新插入行的引用。 |
为 tr元素添加的属性和方法如下。
| 方法 | 描述 |
|---|---|
| cells | 保存着 <tr< 元素中单元格的 HTMLCollection 。 |
| deleteCell(pos) | 删除指定位置的单元格。 |
| insertCell(pos) | 向 cells 集合中的指定位置插入一个单元格,返回对新插入单元格的引用。使用这些属性和方法,可以极大地减少创建表格所需的代码数量。例如,使用这些属性和方法可以将前面的代码重写如下(加阴影的部分是重写后的代码)。 |
//创建 table
var table = document.createElement("table");
table.border = 1;
table.width = "100%";
//创建 tbody
var tbody = document.createElement("tbody");
table.appendChild(tbody);
// 创建第一行
tbody.insertRow(0);
tbody.rows[0].insertCell(0);
tbody.rows[0].cells[0].appendChild(document.createTextNode("Cell 1,1"));
tbody.rows[0].insertCell(1);
tbody.rows[0].cells[1].appendChild(document.createTextNode("Cell 2,1"));
// 创建第二行
tbody.insertRow(1);
tbody.rows[1].insertCell(0);
tbody.rows[1].cells[0].appendChild(document.createTextNode("Cell 1,2"));
tbody.rows[1].insertCell(1);
tbody.rows[1].cells[1].appendChild(document.createTextNode("Cell 2,2"));
//将表格添加到文档主体中
document.body.appendChild(table);
评论
共0 条评论
