gpt4 book ai didi

javascript - 从 JSON 对象生成结构化 HTML

转载 作者:行者123 更新时间:2023-12-03 07:23:47 26 4
gpt4 key购买 nike

我正在尝试想出从下面的 JSON 对象生成表的最佳方法:

mytable=[
{div:{
nested:[
{table:{
nested:[
{thead:{
nested:[
{tr:{
nested:[
{th:{}},
{th:{}},
{th:{}}
]}}
]
}},
{tbody:{}}
]}}
]}}
];

最终结果将生成 HTML 元素,其结构如下:

<div>
<table>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>

我的逻辑是检查对象是否具有属性 nested 如果是,则生成元素并继续循环,但是我不知道如何将子元素绑定(bind)回 parent 同时。

最佳答案

这可以完成工作:

var mytable = /* your json */

function toHTML(j, n) {

n = n || document.createDocumentFragment('div');
for (var i = 0, o, l = j.length; i < l; i++) {
for (var tag in j[i]) {
o = document.createElement(tag);
n.appendChild(o);
'nested' in j[i][tag] && toHTML(j[i][tag].nested, o);
}
}
return n;
}
var res = toHTML(mytable);

// now append it where needed
document.body.appendChild(res);

关于javascript - 从 JSON 对象生成结构化 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36093091/

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