如何使用循环创建表?

3 javascript loops

单个表行给了我一个问题.我用div创建了我想要的东西,但我需要使用表而不是div.我的表有220个单元格,10行和22列.每个单元格都必须具有i内部的值innerHTML.这与我想要的Divs类似(虽然不必设置单元格的高度和宽度):

<!DOCTYPE html>
<html>
    <head>
        <style>
            #container{ 
            width:682px; height:310px; 
            background-color:#555; font-size:85%;
            }

            .cell { 
            width:30px; height:30px;
            background-color:#333; color:#ccc;
            float:left; margin-right:1px;
            margin-bottom:1px;
            }
        </style>
    </head>

    <body>
        <div id="container">
            <script>
                for( var i = 1; i <= 220; i++ ){
                    document.getElementById( 'container' ).innerHTML += 
                    '<div class="cell">' + i + '</div>'
                }
            </script>
        </div>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/8r6619wL/

这是我使用表格的开始尝试:

<script>
    for( var i = 0; i <= 10; i++ )
    {
        document.getElementById( 'table' ).innerHTML +=
        '<tr id = "row' + i + '"><td>...</td></tr>';
    }
</script>
Run Code Online (Sandbox Code Playgroud)

但该代码以某种方式动态地创建了一堆tbody元素.感谢帮助,因为我新手

Stu*_*art 6

您可以使用嵌套循环执行此操作 - 一个用于向每行添加单元格,另一个用于向表中添加行.的jsfiddle

var table = document.createElement('table'), tr, td, row, cell;
for (row = 0; row < 10; row++) {
    tr = document.createElement('tr');
    for (cell = 0; cell < 22; cell++) {
        td = document.createElement('td');
        tr.appendChild(td);
        td.innerHTML = row * 22 + cell + 1;
    }
    table.appendChild(tr);
}
document.getElementById('container').appendChild(table);
Run Code Online (Sandbox Code Playgroud)

或者,您可以创建一个22行单元格的空行,将其克隆10次,然后将数字添加到单元格中.

var table = document.createElement('table'),
    tr = document.createElement('tr'),
    cells, i;
for (i = 0; i < 22; i++) { // Create an empty row
    tr.appendChild(document.createElement('td'));
}
for (i = 0; i < 10; i++) { // Add 10 copies of it to the table
    table.appendChild(tr.cloneNode(true));
}
cells = table.getElementsByTagName('td'); // get all of the cells
for (i = 0; i < 220; i++) {               // number them
    cells[i].innerHTML = i + 1;
}
document.getElementById('container').appendChild(table);
Run Code Online (Sandbox Code Playgroud)

第三个选择:加在一个循环中的细胞,使新行每22个细胞.

var table = document.createElement('table'), tr, td, i;
for (i = 0; i < 220; i++) { 
    if (i % 22 == 0) { // every 22nd cell (including the first)
        tr = table.appendChild(document.createElement('tr')); // add a new row
    }
    td = tr.appendChild(document.createElement('td'));
    td.innerHTML = i + 1;
}
document.getElementById('container').appendChild(table);
Run Code Online (Sandbox Code Playgroud)