使用Javascript创建表我有一个JavaScript函数,它创建一个包含3行2个单元格的表。谁能告诉我如何使用我的功能创建下表(我需要根据我的情况这样做)?这是我的javascript和html代码,如下所示: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");}<table width="100%" border="1">
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td rowspan="2"> </td>
</tr>
<tr>
<td> </td>
</tr></table>
3 回答
炎炎设计
TA贡献1808条经验 获得超4个赞
function addTable() { var myTableDiv = document.getElementById("myDynamicTable"); var table = document.createElement('TABLE'); table.border = '1'; var tableBody = document.createElement('TBODY'); table.appendChild(tableBody); for (var i = 0; i < 3; i++) { var tr = document.createElement('TR'); tableBody.appendChild(tr); for (var j = 0; j < 4; j++) { var td = document.createElement('TD'); td.width = '75'; td.appendChild(document.createTextNode("Cell " + i + "," + j)); tr.appendChild(td); } } myTableDiv.appendChild(table);}addTable();
<div id="myDynamicTable"></div>
添加回答
举报
0/150
提交
取消