在表格中显示嵌套JSON数组的数据可以通过以下步骤实现:
<table>
元素和相关的表格标签(如<thead>
、<tbody>
和<tr>
)来构建表格的结构。以下是一个示例代码片段,演示如何在HTML表格中显示嵌套JSON数组的数据:
<!DOCTYPE html>
<html>
<head>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: left;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
<script>
// 假设以下JSON数据是从服务器获取的嵌套数组数据
var jsonData = [
{
"name": "John Doe",
"email": "john@example.com",
"phone": [
{
"type": "home",
"number": "1234567890"
},
{
"type": "work",
"number": "0987654321"
}
]
},
{
"name": "Jane Smith",
"email": "jane@example.com",
"phone": [
{
"type": "home",
"number": "9876543210"
},
{
"type": "work",
"number": "0123456789"
}
]
}
];
var tableBody = document.getElementById("tableBody");
// 遍历JSON数据并填充表格
jsonData.forEach(function (item) {
var row = document.createElement("tr");
var nameCell = document.createElement("td");
var emailCell = document.createElement("td");
var phoneCell = document.createElement("td");
nameCell.textContent = item.name;
emailCell.textContent = item.email;
// 处理嵌套的phone数组数据
var phoneNumbers = "";
item.phone.forEach(function (phone) {
phoneNumbers += phone.type + ": " + phone.number + "<br>";
});
phoneCell.innerHTML = phoneNumbers;
row.appendChild(nameCell);
row.appendChild(emailCell);
row.appendChild(phoneCell);
tableBody.appendChild(row);
});
</script>
</body>
</html>
这个示例代码会创建一个包含姓名、电子邮件和电话号码的表格,并在电话号码列中显示嵌套的JSON数组数据。你可以根据实际需求进行修改和扩展。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云