【问题标题】:Generate html table from json data with different table header other than json key从 json 数据生成 html 表,其表头与 json 键不同
【发布时间】:2021-08-16 19:38:10
【问题描述】:

我有 json 文件


    [
        {
            "id": "1234",
            "desc": "desc",
            "author": "abcd"
        },
        {
            "id": "1234",
            "desc": "desc",
            "author": "abcd"
        },
        {
            "id": "1234",
            "desc": "desc",
            "author": "abcd"

        }
    ]
}

需要使用 JavaScript 从JSON 生成动态 html 表,并且列标题不应该是 JSON 键。并且列标题的值应该是

Book ID |Book name|Author name | SUBMIT

|:----  |:------:|       -----:|--------:|

| One   | Two    |       Three |Four:|

在第 4 列,应该是一个带有onclick 功能的按钮。

我试图生成表格。但无法将JSON 值映射到除JSON 键之外的列标题名称。以及如何使用按钮添加额外的列。

<!DOCTYPE html>
<html>
<head>
    <style>
        th, td, p, input, h3 {
            font:15px 'Segoe UI';
        }
        table, th, td {
            border: solid 1px #ddd;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
        }
        th {
            font-weight:bold;
        }
    </style>
</head>
<body>
<input type='button' onclick='tableFromJson()'
       value='Submitted Books' />

<p id='showData'></p>

<p id='msg'></p>
</body>


</html>

以上代码将生成具有 3 个标题和标题名称作为 json 键的表。在 col[] 里面,如果我给出正确的列标题,那么它就没有正确映射

【问题讨论】:

  • 这与Java无关,请在提问时仅提供相关标签
  • “我试图生成表格” - 请您将此问题添加为minimal reproducible example
  • 以上代码将生成具有 3 个标头和标头名称作为 json 键的表。在 col[] 里面,如果我给出正确的列标题,那么它就没有正确映射
  • 第四列的内容文本是什么?
  • 第4列,应该是一个带有onclick功能的按钮。

标签: javascript html html-table


【解决方案1】:

你做的几乎是正确的,但我认为顺序是错误的。

for (var i = 0; i < col.length; i++) { // only for table cells, not header
  var th = document.createElement("th"); // should be outside loop
  th.innerHTML = col[i]; // table cells
  tr.appendChild(th); // this will append 3 headers, each time on the loop
}

你应该改用类似的东西:

var th = document.createElement("th")

for (var i = 0; i < col.length; i++) {
  var tabCell = th.insertCell(-1)
  tabCell.innerHTML = col[i]
}

tr.appendChild(th)

这只是一个粗略的想法给你看,我自己没有测试过,只是使用你所做的并稍微改变了它。

【讨论】:

    【解决方案2】:

    我稍微重构了你的代码。我用forEach() 替换了for 循环,我发现它更易读。

    表格中按钮的事件侦听器位于保存表格的&lt;div&gt; 上。原因是如果再次呈现表,您不需要分配新的事件侦听器。您唯一需要做的就是测试它是否是被点击的按钮。

    var submitBooks = document.getElementById('submitBooks');
    var showData = document.getElementById('showData');
    
    submitBooks.addEventListener('click', tableFromJson);
    
    showData.addEventListener('click', e => {
      if(e.target.nodeName == 'BUTTON'){
        console.log(e.target.attributes.item('data-id').value);
      }
    });
    
    function tableFromJson() {
      // the json data. (you can change the values for output.)
      var details = [{
          "id": "11256310",
          "desc": "desc",
          "author": "abc",
    
        },
        {
          "id": "33856310",
          "desc": "desca",
          "author": "abcA",
    
        },
        {
          "id": "73856310",
          "desc": "descB",
          "author": "cBonfigadminB",
    
        }
      ];
    
      // Extract value from table header.
    
      var cols = ['id', 'desc', 'author', 'submit'];
    
    
      // Create a table.
      var table = document.createElement("table");
    
      // Create table header row
      var tr = table.insertRow(); // table row.
    
      cols.forEach(col => {
        let th = document.createElement("th"); // table header.
        th.innerHTML = col;
        tr.appendChild(th);
      });
    
      // add json data to the table as rows.
      details.forEach(detail => {
        let tr = table.insertRow();
        Object.keys(detail).forEach(key => {
          let tabCell = tr.insertCell();
          tabCell.innerHTML = detail[key];
        });
        let tabCell = tr.insertCell();
        let button = document.createElement('BUTTON'); // create button
        button.textContent = 'Submit';
        let dataid = document.createAttribute('data-id'); // attribute for button what holds id
        dataid.value = detail.id;
        button.attributes.setNamedItem(dataid);
        tabCell.append(button);
      });
    
    
      // Now, add the newly created table with json data, to a container.
      var divShowData = document.getElementById('showData');
      divShowData.innerHTML = "";
      divShowData.appendChild(table);
    }
    th,
    td,
    p,
    input,
    h3 {
      font: 15px 'Segoe UI';
    }
    
    table,
    th,
    td {
      border: solid 1px #ddd;
      border-collapse: collapse;
      padding: 2px 3px;
      text-align: center;
    }
    
    th {
      font-weight: bold;
    }
    <input id="submitBooks" type='button' value='Submitted Books' />
    <p id='showData'></p>
    <p id='msg'></p>

    【讨论】:

      猜你喜欢
      • 2014-06-29
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-15
      • 2011-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多