Javascript 如何使用循环创建表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27594957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:21:53  来源:igfitidea点击:

How to create a table using a loop?

javascriptloops

提问by Stuart

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 iinside the innerHTML. Here is similar to what i want using Divs ( although the cell height and width does not have to be set ):

单个表格行给我带来了问题。我已经使用 div 创建了我想要的东西,但我需要使用表格而不是 div。我的表格有 220 个单元格、10 行和 22 列。每个单元格都必须iinnerHTML. 这类似于我想要使用 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>

http://jsfiddle.net/8r6619wL/

http://jsfiddle.net/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>

But that code somehow dynamically creates a bunch of tbody elements. Thanks for help as I newb

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

回答by Stuart

You can do this with nested loops - one to add cells to each row and one to add rows to the table. JSFiddle

您可以使用嵌套循环来执行此操作 - 一个用于向每一行添加单元格,另一个用于向表格添加行。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);

Alternatively, you can create an empty row of 22 cells, clone it 10 times, and then add the numbers to the cells.

或者,您可以创建一个包含 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);

And a third option: add the cells in a single loop, making a new row every 22 cells.

第三个选择:加在一个循环中的细胞,使新行每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);

回答by psdpainter

There are a lot of ways to do this, but one I've found to be helpful is to create a fragmentthen append everything into it. It's fast and limits DOM re-paints/re-flows from a loop.

有很多方法可以做到这一点,但我发现一种有用的方法是创建一个fragment然后将所有内容附加到其中。它很快并且限制了循环中的 DOM 重绘/重流。

Take a look at this jsbin example.

看看这个jsbin 示例

Here's the modified code:

这是修改后的代码:

function newNode(node, text, styles) {
  node.innerHTML = text;
  node.className = styles;
  return node;
}

var fragment = document.createDocumentFragment(),
  container = document.getElementById("container");

for(var i = 1; i <= 10; i++) {
  var tr = document.createElement("tr");
  var td = newNode(document.createElement("td"), i, "cell");
  tr.appendChild(td);
  fragment.appendChild(tr);
}

container.appendChild(fragment);

You can modify whatever you want inside the loop, but this should get you started.

您可以在循环内修改任何您想要的内容,但这应该会让您开始。

回答by caleb531

That's because the DOMmagically wraps a <tbody>element around stray table rows in your table, as it is designed to do. Fortunately, you can rewrite your loop in a way that will add allof those table rows at once, rather than one at a time.

那是因为DOM神奇地将<tbody>元素包裹在表中的杂散表行周围,正如其设计的那样。幸运的是,您可以通过一次添加所有这些表行而不是一次添加一个的方式来重写循环。

The simplest solution to achieve this would be to store a string variable, and concatenate your rows onto that. Then, after you've concatenated your rows together into one string, you can set the innerHTMLof your table element to that one string like so:

实现这一点的最简单的解决方案是存储一个字符串变量,并将您的行连接到该变量上。然后,在将行连接成一个字符串后,您可以将innerHTMLtable 元素的 设置为该字符串,如下所示:

<script>
(function() {
    var rows = '';
    for( var i = 0; i <= 10; i++ )
    {
        rows += '<tr id = "row' + i + '"><td>...</td></tr>';
    }
    document.getElementById( 'table' ).innerHTML = rows;
}());
</script>

Here's a JSFiddlethat demonstrates what I've just written. If you inspect the HTML using your browser's developer tools, you'll notice that one (and only one) tbodywraps around allof your table rows.

这是一个 JSFiddle,它演示了我刚刚编写的内容。如果您使用浏览器的开发人员工具检查 HTML,您会注意到一个(并且只有一个)tbody环绕您的所有表格行。

Also, if you're wondering, the odd-looking function which wraps around that code is simply a fancy way of keeping the variables you've created from becoming global (because they don't need to be). See this blog postfor more details on how that works.

此外,如果您想知道,环绕该代码的看起来很奇怪的函数只是一种防止您创建的变量成为全局变量的奇特方式(因为它们不需要成为)。有关其工作原理的更多详细信息,请参阅此博客文章