HTML DOM中对于操作表格内置了一系列的属性和方法,通过js可以方便的创建表格。
caption | <caption>的指针 |
tBodies | <tbody>的HTMLCollection(类数组搜集对象) |
tFoot | <tfoot>的指针 |
tHead | <thead>的指针 |
rows | 保存所有行的HTMLCollection |
createTHead() | 创建<thead>的方法,返回引用 |
createTFoot() | 创建<tfoot>的方法,返回引用 |
createCaption() | 创建<caption>的方法,返回引用 |
deleteTFoot() | 删除<tfoot> |
deleteTHead() | 删除<thead> |
deleteCaption() | 删除<caption> |
deleteRow(pos) | 删除行 |
insertRow(pos) | 插入行 |
cells | 保存<tr>中单元格的HTMLCollection |
如下为使用这种方式来创建一个表格和直接操作DOM来创建一个表格对比:
// js 操作dom
// var body = document.documentElement;
var body = document.body;
var table = document.createElement("table");
table.setAttribute("border", "1");
table.setAttribute("width", "100%")
body.appendChild(table);
var tbody = document.createElement("tbody");
table.appendChild(tbody);
var tr1 = document.createElement("tr");
tbody.appendChild(tr1);
var cell1_1 = document.createElement("td");
cell1_1.appendChild(document.createTextNode("cell 1, 1"));
tr1.appendChild(cell1_1);
var cell1_2 = document.createElement("td");
cell1_2.appendChild(document.createTextNode("cell 1, 2"));
tr1.appendChild(cell1_2);
var tr2 = document.createElement("tr");
tbody.appendChild(tr2);
var cell2_1 = document.createElement("td");
cell2_1.appendChild(document.createTextNode("cell 2, 1"));
tr2.appendChild(cell2_1);
var cell2_2 = document.createElement("td");
cell2_2.appendChild(document.createTextNode("cell 2, 2"));
tr2.appendChild(cell2_2);
body.appendChild(document.createElement("br"));
body.appendChild(document.createElement("hr"));
body.appendChild(document.createElement("br"));
// DOM 表格属性方法使用
var table2 = document.createElement("table");
table2.setAttribute("border", "1");
table2.setAttribute("width", "100%")
body.appendChild(table2);
var tbody2 = document.createElement("tbody");
table2.appendChild(tbody2);
tbody2.insertRow(0); // 插入第一行
tbody2.rows[0].insertCell(0); // 插入行中第一个格
tbody2.rows[0].cells[0].appendChild(document.createTextNode("cell 1, 1"));
tbody2.rows[0].insertCell(1); // 插入行中第二个格
tbody2.rows[0].cells[1].appendChild(document.createTextNode("cell 1, 2"));
tbody2.insertRow(1); // 插入第二行
tbody2.rows[1].insertCell(0);
tbody2.rows[1].cells[0].appendChild(document.createTextNode("cell 2, 1"));
tbody2.rows[1].insertCell(1);
tbody2.rows[1].cells[1].appendChild(document.createTextNode("cell 2, 2"));