gpt4 book ai didi

javascript - 从 JSON 数据创建 html 表

转载 作者:行者123 更新时间:2023-11-28 13:13:45 28 4
gpt4 key购买 nike

我有一个 html 文件,其中包含此代码片段。

<div>
<table id="apps"></table>
</div>

我收到的 JSON 数据如下所示:

{
"1": [
{
"A": "",
"B": "",
"C": "",
"D": "",
"E": ""
}
]
}

只有一个 "1" ,但 "1" 列表中可以有多个字典。在此示例中,列表 [] 中只有一个 {},但可以存在多个恰好包含五个项目的 {}就像上面显示的那样。

我想根据这些数据创建一个表,其中每一行代表 [] 内的一个 {},并有五列代表 A、B、C、分别为D、E。

我不确定我是否应该拥有这个结构,标签已经在我的html中(这不在我提供的html代码中),然后填充这些标签,或者我应该在我的html文件中加载这些数据的函数,访问table id="apps"并创建这些标签,然后填充这些标签?哪个更好?以及如何有效地实现这一目标?

最佳答案

尝试这个简单的工作示例。我希望它能按照您的期望工作。

var dataObj = {
"1": [{
"A": "",
"B": "",
"C": "",
"D": "",
"E": ""
},
{
"F": "",
"G": "",
"H": "",
"I": "",
"J": ""
},
{
"K": "",
"L": "",
"M": "",
"N": "",
"O": ""
}
]};

var dictionaryData = dataObj["1"];

for (var i in dictionaryData) {
var table = document.getElementById("apps");
var tr = document.createElement("tr");
var td = document.createElement("td");

for (var key in dictionaryData[i]) {
var txt = document.createTextNode(key);
td.appendChild(txt);
tr.appendChild(td);
}
table.appendChild(tr);
}
table, td {
border: 1px solid black;
}
<div>
<table id="apps"></table>
</div>

关于javascript - 从 JSON 数据创建 html 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40413048/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com