html动态表值



im对编码很陌生,并尝试构建一个动态表。第1列工作良好,每个新单元格都位于顶部。我想在第二个第三个等等做同样的事情。但当我试图将列添加到表中时,从上到下填充。我想让我的桌子看起来像

5|5|5
4|4|4
3|3|3
2|2|2
1|1|1
0|0|0 

function createcolumn() {
for (var i = 0; i < 6; i++){
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
cell1.innerHTML = "NEW CELL1 - "+i;

}
}
function createCell(cell, text, style) {
var div = document.createElement('div'), // create DIV element
txt = document.createTextNode(text); // create text node
div.appendChild(txt);                    // append text node to the DIV
div.setAttribute('class', style);        // set DIV class attribute
div.setAttribute('className', style);    // set DIV class attribute for IE (?!)
cell.appendChild(div);                   // append DIV to the table cell
}
function addcolumn() {
var tbl = document.getElementById('myTable'), // table reference
i;
// open loop for each row and append cell
//for (i = 0; i < tbl.rows.length; i++) {
for (i = 5; i < tbl.rows.length; i--) {
createCell(tbl.rows[i].insertCell(tbl.rows[i].cells.length), i, 'col');
}
}
table, td {
border: 1px solid black;
}
<p>Click the button to add a new row at the first position of the table and then add cells and content.</p>
<table id="myTable">
</table>
<br>
<button type="button" onclick="createcolumn()">1st column</button>
<button type="button" onclick="addcolumn()">add column</button>
<p id="demo"></p>

使用add column函数,您可以执行5-i而不是仅执行i,这将显示您想要的内容。

createCell(tbl.rows[i].insertCell(tbl.rows[i].cells.length), 5-i, 'col');

最新更新