您好,我希望我的陣列使用陣列中的資訊為我創建一個表
我已經創建了一個表,但是我無法傳遞到表中,為什么?我希望它自動創建一個表,如果可以使用表 ID,那就太好了
<table class="col-3 table tableforContact" id="contactinformation">
<thead>
<tr>
</tr>
</thead>
<tbody>
</tbody>
</table>
這就是我讓 json 決議我的陣列的方式
const responses = JSON.parse(user.Contacts)
console.log(responses)
并得到這個陣列
在此處輸入影像描述
這就是我的陣列回應的樣子
[{"ContactName": "45551134", "ContactNumber": "95011225"}]
uj5u.com熱心網友回復:
您可以遍歷資料陣列并將每個物件附加到一行:
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/[email protected]/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>
uj5u.com熱心網友回復:
可以使用 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/417911.html
標籤:
下一篇:如何使用泛型陣列-SwiftUI
