【问题标题】:Create dynamic html table using javascript from simple array使用简单数组中的 javascript 创建动态 html 表
【发布时间】:2018-10-11 08:16:43
【问题描述】:

我想编写一些 JavaScript 来从仅包含数字的数组创建一个简单的 HTML 表:

var array = [1,2,3,4,5,6,7,8,9,10];

表格应如下所示:

1 2 3 4 5
6 7 8 9 10

但是 JavaScript 代码应该是动态的,具体取决于数组大小(尽管总是 5 倍)。

我尝试了很多东西,但它从来没有按照我想要的方式工作。实现这一目标的最简单方法是什么?

这是我的尝试之一。

var tableStart = "<table border>";
for (i = 0; i < arraySize/5; i++){
  var tableMiddle = "<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>"
  if (arraySize/5 >= 2) {
    tableMiddle = tableMiddle + tableMiddle;
  }
};
var tableEnd = "</table>";
var table = tableStart.concat(tableMiddle, tableEnd);

还有

var result = "<table border=1>";
for(var i=0; i<2; i++) {
    result += "<tr>";
    for(var j=0; j<array.length; j++){
        result += "<td>"+array[i]+"</td>";
    }
    result += "</tr>";
}
result += "</table>";

这只会导致数组的两个值被显示很多次。

【问题讨论】:

  • 嗨@Alexander - 欢迎来到 SO。你能展示你到目前为止尝试过的代码吗?
  • 当然是@itamar

标签: javascript html css arrays html-table


【解决方案1】:

尝试这样的事情怎么样?代码中的解释。此外,未经测试,因此您可能需要进行一些调整。

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// start the table
var table = document.createElement("table");
var currentRow;
for (var i = 0; i < array.length; i++) {
  // put items in.
  var item = document.createElement("td");
  item.innerHTML = array[i];
  // if we are at the 
  if (i % 5 === 0) {
    // if it's not the first time you're creating row - first put the prev row into the table, then reassign it to a new table row.
    if (typeof currentRow !== 'undefined') table.appendChild(currentRow);
  currentRow.appendChild(item);

    currentRow = document.createElement("tr");
  }

}
// put the table into the body element, for example.
document.getElementsByTagName('body')[0].appendChild(table);

【讨论】:

  • (1 % 5 === 0) 永远是假的
【解决方案2】:

var array = [1,2,3,4,5,6,7,8,9,10];

var result = "<table border=1>";
result += "<tr>";
for (var j = 0; j < array.length; j++) {
  result += "<td>" + array[j] + "</td>";
  if ((j + 1) % 5 == 0) {
    result += "</tr><tr>";
  }
}
result += "</tr>";
result += "</table>";

document.body.innerHTML = result;

如果可行,请试一试

【讨论】:

    【解决方案3】:

    如果余数为 5,则可以迭代数组并构建一个新行。

    var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
        tr;
    
    array.forEach((v, i) => {
        var td = document.createElement('td');
        
        if (!(i % 5)) {
            tr = document.createElement('tr');
            document.getElementById('table0').appendChild(tr);
        }
        td.appendChild(document.createTextNode(v));
        tr.appendChild(td);
    });
    &lt;table id="table0"&gt;&lt;/table&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      • 2018-02-27
      • 2020-09-22
      相关资源
      最近更新 更多