【问题标题】:How to create a HTML table from an array?如何从数组创建 HTML 表格?
【发布时间】:2022-01-22 20:27:12
【问题描述】:
我想用数组中的信息创建一个表。我创建了一个表,但是我无法将数组传递到表中。
我希望它从数组中自动创建一个表。
<table class="col-3 table tableforContact" id="contactinformation">
<thead>
<tr>
</tr>
</thead>
<tbody>
</tbody>
</table>
这就是我定义数组的方式:
const responses = JSON.parse(user.Contacts)
最后,这是数组中的内容:
[{"ContactName": "45551134", "ContactNumber": "95011225"}]
【问题讨论】:
标签:
javascript
arrays
html-table
【解决方案1】:
您可以遍历数据数组并将每个对象附加到一行:
const data = [{"ContactName": "45551134", "ContactNumber": "95011225"}];
const table = document.querySelector("#contactinformation");
const headers = table.querySelector("thead tr");
const body = table.querySelector("tbody");
// Create headers
for (const key in data[0]) {
const header = document.createElement("th");
header.innerText = key;
headers.append(header);
}
// Create tbody rows
data.forEach(obj => {
// Create row
const row = document.createElement("tr");
body.append(row);
// Create row element
for (const key in obj) {
const value = document.createElement("td");
value.innerText = obj[key];
row.append(value);
}
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<table class="col-3 table tableforContact" id="contactinformation">
<thead>
<tr>
</tr>
</thead>
<tbody>
</tbody>
</table>
【解决方案2】:
可以使用 jQuery 吗?如果是,您可以使用$.each 函数。
const array = [{"ContactName": "45551134", "ContactNumber": "95011225"}]
$.each(array, function(index){
$("#contact-name").html(this.ContactName)
$("#contact-number").html(this.ContactNumber)
});
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
<table class="col-3 table tableforContact" id="contactinformation">
<thead>
<tr>
<td>Contact Name</td>
<td>Contact Number</td>
</tr>
</thead>
<tbody>
<tr>
<td id="contact-name"></td>
<td id="contact-number"></td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>