首页 > 解决方案 > 如何使用带有 foreach 循环的 javascript 呈现表格

问题描述

我有一个表,它的 tr 需要通过渲染 td 中的值来重复。td 的值来自使用 foreach 循环的 get api 调用。我已经尝试渲染,但我的 tbody 没有进入桌子。我希望它只使用javascript创建,没有jquery。这是下面的代码

var container = document.getElementById("container");
var url = "http://dummy.restapiexample.com/api/v1/employees";
fetch(url).then(function(response) {
  return response.json();
}).then(function(data) {
  container.innerHTML = '<div class="container"><h2>Basic Table</h2><p>The .table class adds basic styling (light padding and horizontal dividers) to a table:</p><table class="table"><thead><tr><th>ID</th><th>Firstname</th></tr></thead>'
  data.data.forEach(function(count) {
    console.log(count);
    container.innerHTML += '<tbody><tr><td>' + count.id + '</td><td>' + count.employee_name + '</td></tr></tbody>';
  })
}).catch(function() {
  console.log("Booo");
});
container.innerHTML = '</table></div>'
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<div id="container">
  <h2>Basic Table</h2>
  <p>The .table class adds basic styling (light padding and horizontal dividers) to a table:</p>
</div>

标签: javascripthtml

解决方案


从开始创建表格和 tbody 并使用 forEach 插入行

var container = document.getElementById("container");
var url = "http://dummy.restapiexample.com/api/v1/employees";
fetch(url).then(function(response) {
  return response.json();
}).then(function(data) {
  data.data.forEach(function(count) {
    console.log(count);
    let tableBody = document.getElementById("tableBody");
    tableBody.innerHTML += '<tr><td>' + count.id + '</td><td>' + count.employee_name + '</td></tr>';
  })
}).catch(function() {
  console.log("Booo");
});
container.innerHTML = '</table></div>'
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>

<body>
  <div id="container">
    <h2>Basic Table</h2>
    <p>The .table class adds basic styling (light padding and horizontal dividers) to a table:</p>
    <table class="table">
       <thead>
         <tr>
          <th>ID</th><th>Firstname</th>
         </tr>
        </thead>
        <tbody id="tableBody">
        </tbody>
    </table>
  </div>


推荐阅读