簡體   English   中英

從JSON對象生成結構化HTML

[英]Generating structured HTML from JSON object

我正在嘗試提出從下面的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的屬性(如果生成該元素並繼續循環),但是我無法弄清楚如何將子元素同時綁定回父元素。

這可以工作:

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM