单个表行给我一个问题。我用div创建了我想要的东西,但我需要使用表而不是div。我的表有220个单元格,10行和22列。每个单元格必须在 innerHTML 中包含 i 的值。这与我想要的Divs相似(尽管不必设置单元格的高度和宽度):
The individual table rows are giving me a problem. I have created what I want using divs but I need to use a table instead of divs. My table has 220 cells, 10 rows, and 22 columns. Each cell has to have the value of i inside the innerHTML. Here is similar to what i want using Divs ( although the cell height and width does not have to be set ):
<!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>jsfiddle/8r6619wL/
这是我使用表格的首次尝试:
This is my starting attempt using a table:
<script> for( var i = 0; i <= 10; i++ ) { document.getElementById( 'table' ).innerHTML += '<tr id = "row' + i + '"><td>...</td></tr>'; } </script>但该代码以某种方式动态创建了一堆tbody元素。感谢您的帮助,因为我新手
But that code somehow dynamically creates a bunch of tbody elements. Thanks for help as I newb
推荐答案您可以使用嵌套循环执行此操作 - 一个用于向每行添加单元格,另一个用于添加行到表。 JSFiddle
You can do this with nested loops - one to add cells to each row and one to add rows to the table. 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);或者,您可以创建一个22行单元格的空行,将其克隆10次,然后将数字添加到单元格中。
Alternatively, you can create an empty row of 22 cells, clone it 10 times, and then add the numbers to the cells.
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);以及第三个选项:在单个循环中添加单元格,每22个单元格生成一个新行。
And a third option: add the cells in a single loop, making a new row every 22 cells.
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);更多推荐
如何使用循环创建表?
发布评论