星空网 > 软件开发 > Java

DOM操作表格实例

要求

<table border = "1" width = "100%">  <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>

 

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为<table>、<tbody>、<tr>元素添加了属性和方法。

  【1】为<table>元素添加的属性和方法

caption:保存着对<caption>元素的指针tBodies:是一个<tbody>元素的HTMLCollectiontFoot:保存着对<tfoot>元素的指针tHead:保存着对<thead>元素的指针createTHead():创建<thead>元素,将其放到表格中,返回引用createTFoot():创建<tfoot>元素,将其放到表格中,返回引用createCaption():创建<caption>元素,将其放到表格中,返回引用deleteTHead():删除<thead>元素deleteTFoot():删除<tfoot>元素deleteCaption():删除<caption>元素

 

  【2】为<tbody>元素添加的属性和方法

rows:保存着<tbody>元素中行的HTMLCollectiondeleteRow(pos):删除指定位置的行insertRow(pos):向rows集合中的指定位置插入一行,返回对新插入行的引用

 

  【3】为<tr>元素添加的属性和方法

cells:保存着<tr>元素中单元格的HTMLCollectiondeleteCell(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);

 

效果展示

 

【源码查看】




原标题:DOM操作表格实例

关键词:dom

dom
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

易仓云ERP:https://www.ikjzd.com/w/1422
方信知识产权公司:https://www.ikjzd.com/w/1423
wish店铺排名:https://www.ikjzd.com/w/1424
数魔跨境:https://www.ikjzd.com/w/1425
亚易知识产权_深圳市亚易知识产权代理有限公司:https://www.ikjzd.com/w/1426
转口贸易:https://www.ikjzd.com/w/1427
珠海市图书馆官网入口:https://www.vstour.cn/a/335174.html
珠海图书馆几点开门几点关门?附营业时间:https://www.vstour.cn/a/335175.html
相关文章
我的浏览记录
最新相关资讯
跨境电商服务平台 | 深圳旅行社 | 东南亚物流