前面的话
表格table元素是HTML中最复杂的结构之一。要想创建表格,一般都必须涉及表示表格行、单元格、表头等方面的标签。由于涉及的标签多,因而使用核心DOM方法创建和修改表格往往都免不了要编写大量的代码。本文将详细介绍DOM操作表格的属性和方法

创新互联公司为企业级客户提高一站式互联网+设计服务,主要包括网站制作、
网站建设、
重庆APP开发公司、
小程序开发、宣传片制作、LOGO设计等,帮助客户快速提升营销能力和企业形象,创新互联各部门都有经验丰富的经验,可以确保每一个作品的质量和创作周期,同时每年都有很多新员工加入,为我们带来大量新的创意。
需求
要通过DOM实现下列格式的表格结构

Cell 1,1 |
Cell 2,1 |
Cell 1,2 |
Cell 2,2 |

DOMcore
如果通过DOMcore方法,则方法如下

//创建表格var table = document.createElement("table");
table.border = "1";
table.width = "100%";//创建tbodyvar tbody = document.createElement("tbody");
table.appendChild(tbody);//创建第一行var row1 = document.createElement("tr");
tbody.appendChild(row1);var cell1_1 = document.createElement("td");
cell1_1.appendChild(document.createTextNode("Cell 1,1"));
row1.appendChild(cell1_1);var cell2_1 = document.createElement("td");
cell2_1.appendChild(document.createTextNode("Cell 2,1"));
row1.appendChild(cell2_1);//创建第二行var row2 = document.createElement("tr");
tbody.appendChild(row2);var cell1_2 = document.createElement("td");
cell1_2.appendChild(document.createTextNode("Cell 1,2"));
row2.appendChild(cell1_2);var cell2_2 = document.createElement("td");
cell2_2.appendChild(document.createTextNode("Cell 2,2"));
row2.appendChild(cell2_2);//将表格添加到文档主体中document.body.appendChild(table);

属性和方法
显然DOM代码很长,为了方便构建表格,HTML DOM为
、、元素添加了属性和方法。【1】为
元素添加的属性和方法
caption:保存着对元素的指针
tBodies:是一个元素的HTMLCollection
tFoot:保存着对元素的指针
tHead:保存着对元素的指针
createTHead():创建元素,将其放到表格中,返回引用
createTFoot():创建元素,将其放到表格中,返回引用
createCaption():创建元素,将其放到表格中,返回引用
deleteTHead():删除元素
deleteTFoot():删除元素
deleteCaption():删除元素
【2】为
元素添加的属性和方法rows:保存着元素中行的HTMLCollection
deleteRow(pos):删除指定位置的行
insertRow(pos):向rows集合中的指定位置插入一行,返回对新插入行的引用【3】为
元素添加的属性和方法cells:保存着元素中单元格的HTMLCollection
deleteCell(pos):删除指定位置的单元格
insertCell(pos):向cells集合中的指定位置插入一个单元格,返回对新插入单元格的引用代码重写

//创建表格var table = document.createElement("table");
table.border = "1";
table.width = "100%";//创建tbodyvar 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);

效果展示
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
网站栏目:DOM操作表格-创新互联
文章网址:http://cxhlcq.com/article/igddg.html
-
在线咨询

微信咨询


电话咨询
-
028-86922220(工作日)
18980820575(7×24)
-

提交需求
-

返回顶部