表格是 HTML 中最复杂的结构之一。通过 DOM 编程创建
元素,通常要涉及大量标签,包括表行、表元、表题,等等。因此,通过 DOM 编程创建和修改表格时可能要写很多代码。假设要通过DOM 来创建以下 HTML 表格: <tbody>
<tr>
<td>Cell 1,1</td>
<td>Cell 2,1</td>
</tr>
<tr>
<td>Cell 1,2</td>
<td>Cell 2,2</td>
</tr>
</tbody>
</table>
下面就是以 DOM 编程方式重建这个表格的代码:
let table = document.createElement("table");
table.border = 1;
table.width = "100%";
// 创建表体
let tbody = document.createElement("tbody");
table.appendChild(tbody);
// 创建第一行
let row1 = document.createElement("tr");
tbody.appendChild(row1);
let cell1_1 = document.createElement("td");
cell1_1.appendChild(document.createTextNode("Cell 1,1"));
row1.appendChild(cell1_1);
let cell2_1 = document.createElement("td");
cell2_1.appendChild(document.createTextNode("Cell 2,1"));
row1.appendChild(cell2_1);
// 创建第二行
let row2 = document.createElement("tr");
tbody.appendChild(row2);
let cell1_2 = document.createElement("td");
cell1_2.appendChild(document.createTextNode("Cell 1,2"));
row2.appendChild(cell1_2);
let cell2_2= document.createElement("td");
cell2_2.appendChild(document.createTextNode("Cell 2,2"));
row2.appendChild(cell2_2);
// 把表格添加到文档主体
document.body.appendChild(table);
以上代码相当烦琐,也不好理解。为了方便创建表格,HTML DOM 给
、和元素添加了一些属性和方法。 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),在行集合中给定位置插入一行。
<tbody>元素添加了以下属性和方法:
rows,包含<tbody>元素中所有行的 HTMLCollection;
deleteRow(pos),删除给定位置的行;
insertRow(pos),在行集合中给定位置插入一行,返回该行的引用。
<tr>元素添加了以下属性和方法:
cells,包含<tr>元素所有表元的 HTMLCollection;
deleteCell(pos),删除给定位置的表元;
insertCell(pos),在表元集合给定位置插入一个表元,返回该表元的引用。
这些属性和方法极大地减少了创建表格所需的代码量。例如,使用这些方法重写前面的代码之后是这样的(加粗代码表示更新的部分):
let table = document.createElement("table");
table.border = 1;
table.width = "100%";
// 创建表体
let 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);
这里创建
和元素的代码没有变。变化的是创建两行的部分,这次使用了 HTML DOM 表格的属性和方法。创建第一行时,在元素上调用了 insertRow()方法。传入参数 0,表示把这一行放在什么位置。然后,使用 tbody.rows[0]来引用这一行,因为这一行刚刚创建并被添加到了的位置 0。创建表元的方式也与之类似。在元素上调用 insertCell()方法,传入参数 0,表示把这个表元放在什么位置上。然后,使用 tbody.rows[0].cells[0]来引用这个表元,因为这个表元刚刚创建并被添加到了的位置 0。虽然以上两种代码在技术上都是正确的,但使用这些属性和方法创建表格让代码变得更有逻辑性,
也更容易理解。