我有一个JavaScript函数,它创建一个3行2单元格的表格。
有人可以告诉我如何使用我的功能创建下表(我需要为我的情况做到这一点)?使用Javascript创建表格
我的HTML:
<table width="100%" border="1">
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td rowspan="2"> </td>
</tr>
<tr>
<td> </td>
</tr>
</table>
的JavaScript:
function tableCreate() {
//body reference
var body = document.getElementsByTagName("body")[0];
// create elements <table> and a <tbody>
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
// cells creation
for (var j = 0; j <= 2; j++) {
// table row creation
var row = document.createElement("tr");
for (var i = 0; i < 2; i++) {
// create element <td> and text node
//Make text node the contents of <td> element
// put <td> at end of the table row
var cell = document.createElement("td");
var cellText = document.createTextNode("cell is row "+j+", column "+i);
cell.appendChild(cellText);
row.appendChild(cell);
}
//row added to end of table body
tblBody.appendChild(row);
}
// append the <tbody> inside the <table>
tbl.appendChild(tblBody);
// put <table> in the <body>
body.appendChild(tbl);
// tbl border attribute to
tbl.setAttribute("border", "2");
}
好的解决办法,但最好到循环 –
@Cerbrus之外创建的变量,这是件好事解决方案,但它不能在IE8之前工作。表被添加到DOM资源管理器,但不知何故,它不可见。有人知道如何解决这个问题吗? – bdogru
@bdogru:你为什么需要支持IE8?这是古老的。谷歌[2012年末[浏览器下载]](http://www.computerworld.com/article/2492571/web-apps/google-to-drop-support-for-ie8-on-nov--15.html) – Cerbrus