简体   繁体   English

HTML 表:一个数据多行? Javascript

[英]HTML table: multiple rows for one data? Javascript

I want to have multiple rows for one data set using HTML table.我想使用 HTML 表为一个数据集设置多行。

var row = 0;

var test = [{
  food: "A",
  grade: ["1", "2", "3", "5"]
},
{
  food: "B",
  grade: ["1", "2"]
},
{
  food: "C",
  grade: ["1"]
},]

var display = document.getElementById("table-body");

var newRow = display.insertRow(row);

var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);

cell1.innerHTML = test[0]["food"]
cell2.innerHTML = test[0]["grade"]
For example:
Food || Grade
---------------
A       || 1
        || 2
        || 3
        || 5
---------------
B.     || 1
       || 2
---------------
C.     || 1

However, I'm only able to have them all listed in one cell ie (1,2,3,5).但是,我只能将它们全部列在一个单元格中,即 (1,2,3,5)。 Any ideas on how to replicate the table above?关于如何复制上表的任何想法?

Use nested loops to add rows for each task.使用嵌套循环为每个任务添加行。 Use the rowspan attribute in the first column to make it fill expand to all the rows for that device's tasks.使用第一列中的rowspan属性使其填充扩展到该设备任务的所有行。

test.forEach(t => {
    t.tasks.forEach((task, i) => {
        let newRow = display.insertRow();
        if (i == 0) {
            let firstCell = newRow.insertCell();
            firstCell.innerText = t.device;
            firstCell.setAttribute('rowspan', t.tasks.length;
        }
        newRow.insertCell().innerText = task;
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM