开发者问题收集

将 JS 数组与 HTML 表连接起来

2021-11-09
327

我用 HTML 创建了一个表格,我需要用 JS 中的数组将该表格连接起来:

805205​​668

但是我在控制台中收到错误:“Uncaught TypeError:无法读取 null 的属性(读取‘insertRow’)” 那里出了什么问题?

3个回答

您可以通过循环遍历国家/地区列表并创建 HTML 字符串来实现此目的。然后,您可以使用类或 ID 选择器将其放入 tbody 中。以下是示例

var country = ["Norway", "Sweden", "Denmark"];
    var capital = ["Oslo", "Stockholm" , "Copenhagen"]

    var bodyString = '';
    $.each(country, function(index, ctry) {
        bodyString += ('<tr><td>'+ctry+'</td><td>'+capital[index]+'</td></tr>');
    });
    $('.countriesTable tbody').html(bodyString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>

  <table class="countriesTable">
      <thead>
          <tr><th>Country</th><th>Capital</th>
      </thead>
      <tbody>
      
      </tbody>
  </table>
</body>
</html>
Anmol Verma
2021-11-09

看起来您的代码有效。这是另一种方法,使用 Array.reduce 创建行并使用 insertAdjacentHTML 追加行。

document.querySelector(`#myTable`).insertAdjacentHTML(
  `beforeEnd`, [
    ["A4", "Audi", "2015", "1234"],
    ["A3", "Audi", "2011", "1542"],
    ["335i", "BMW", "2012", "9874"],
    ["440d", "BMW", "2015", "1975"],
    ["Civic", "Honda", "2002", "6574"],
  ].reduce( (acc, [Modelis, Gamintojas, Metai, VariklioNumeris]) =>
    `${acc}<tr><td>${Modelis}</td><td>${Gamintojas}</td><td>${
        Metai}</td><td>${VariklioNumeris}</td></tr>`, ``)
);
#myTable th:nth-child(n+3):nth-child(-n+4),
#myTable td:nth-child(n+3):nth-child(-n+4) {
  text-align: center;
}
<table id="myTable">
  <caption id=a><b>Automobiliai</caption></b>
    <tr>
      <th>Modelis</th>
      <th>Gamintojas</th>
      <th>Metai</th>
      <th>Variklio Numeris</th>
    </tr>
</table>
KooiInc
2021-11-09

您需要将 table 变量定义为 var table =let table = ,并且可以使用 map() 方法进一步优化代码,如以下代码片段所示。

有用的链接:
变量: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Variables

map() 方法: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

var array = [
    ["A4", "Audi", "2015", "1234"],
    ["A3", "Audi", "2011", "1542"],
    ["335i", "BMW", "2012", "9874"],
    ["440d", "BMW", "2015", "1975"],
    ["Civic", "Honda", "2002", "6574"],
]
var table = document.getElementById("myTable");
array.map((v,i)=>{
    var newRow = table.insertRow(table.length);
    array[i].map((val,j)=> {
       var cell = newRow.insertCell(j);
       cell.innerHTML = array[i][j];
    })
});
table{
  border-collapse: collapse;
}
table td,
table th{
  border: 1px solid #dddddd;
  padding: 7px;
}
<table id="myTable">
    <caption id="a"><strong>Automobiliai</strong></caption>
    <tr>
        <th>Modelis</th>
        <th>Gamintojas</th>
        <th>Metai</th>
        <th>Variklio Numeris</th>
    </tr>
</table>
Raeesh Alam
2021-11-09