溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

javascript中如何使用json生成html表格

發(fā)布時間:2020-06-15 10:52:07 來源:億速云 閱讀:280 作者:Leah 欄目:web開發(fā)

javascript中如何使用json生成html表格?相信很多新手小白還沒學會這個技能,通過這篇文章的總結(jié),希望你能學會學會這個技能。以下資料是實現(xiàn)的步驟。

之前公司有一個需求是:通過js來生成html。而且大部分都是生成表格,直接通過字符串拼接的話,代碼的可復用性太低的,所以寫了個通用的json轉(zhuǎn)html表格的工具。

代碼

htmlKit = {
    _tags: [], html: [], 
    _createAttrs: function (attrs) {
        var attrStr = [];
        for (var key in attrs) {
            if (!attrs.hasOwnProperty(key)) continue;
            attrStr.push(key + "=" + attrs[key] + "")
        }
        return attrStr.join(" ")
    }, 
    _createTag: function (tag, attrs, isStart) {
        if (isStart) {
            return "<" + tag + " " + this._createAttrs(attrs) + ">"
        } else {
            return "</" + tag + ">"
        }
    }, 
    start: function (tag, attrs) {
        this._tags.push(tag);
        this.html.push(this._createTag(tag, attrs, true))
    }, 
    end: function () {
        this.html.push(this._createTag(this._tags.pop(), null, false))
    }, 
    tag: function (tag, attr, text) {
        this.html.push(this._createTag(tag, attr, true) + text + this._createTag(tag, null, false))
    }, 
    create: function () {
        return this.html.join("")
    }
};

function json2Html(data) {
    var hk = htmlKit;
    hk.start("table", {"cellpadding": "10", "border": "1"});
    hk.start("thead");
    hk.start("tr");
    data["heads"].forEach(function (head) {
        hk.tag("th", {"bgcolor": "AntiqueWhite"}, head)
    });
    hk.end();
    hk.end();
    hk.start("tbody");
    data["data"].forEach(function (dataList, i) {
        dataList.forEach(function (_data) {
            hk.start("tr");
            data["dataKeys"][i].forEach(function (key) {
                var rowsAndCol = key.split(":");
                if (rowsAndCol.length === 1) {
                    hk.tag("td", null, _data[rowsAndCol[0]])
                } else if (rowsAndCol.length === 3) {
                    hk.tag("td", {"rowspan": rowsAndCol[0], "colspan": rowsAndCol[1]}, _data[rowsAndCol[2]])
                }
            });
            hk.end()
        })
    });
    hk.end();
    hk.end();
    return hk.create()
}

使用說明

HtmlKit

htmlKit是創(chuàng)建html標簽的工具

函數(shù)

函數(shù)名作用例子
start (tag, attrs)創(chuàng)建未封閉標簽頭start("table", {"cellpadding": "10", "border": "1"}),輸出<table cellpadding="10" border="1">
end ()創(chuàng)建上一個start函數(shù)的標簽尾上面執(zhí)行了start("table"),再執(zhí)行end(),輸出</table>
tag (tag, attr, text)創(chuàng)建封閉標簽tag("th", {"bgcolor": "AntiqueWhite"}, "hello"),輸出<th bgcolor="AntiqueWhite">hello</th>

json2Html

json轉(zhuǎn)Html

例子:

var data = [
    {
        "chinese": 80,
        "mathematics": 89,
        "english": 90
    }
];

var total = 0;
data.forEach(function (value) {
    for (key in value) {
        total += value[key];
    }
});

var htmlMetadata = {
    "heads": ["語文", "數(shù)學", "英語"],
    "dataKeys": [["chinese", "mathematics", "english"], ["text","1:2:total"]], // rowspan:colspan:value
    "data": [data, [{"text": "合計","total": total}]]
};

var html = json2Html(htmlMetadata);

console.info(html);

輸出結(jié)果(結(jié)果為了好看,格式化了):

<table cellpadding=10 border=1>
    <thead>
    <tr>
        <th bgcolor=AntiqueWhite>語文</th>
        <th bgcolor=AntiqueWhite>數(shù)學</th>
        <th bgcolor=AntiqueWhite>英語</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>80</td>
        <td>89</td>
        <td>90</td>
    </tr>
    <tr>
        <td>合計</td>
        <td rowspan=1 colspan=2>259</td>
    </tr>
    </tbody>
</table>

效果:

語文數(shù)學英語
808990
合計259

看完這篇文章,你們學會javascript中使用json生成html表格的方法了嗎?如果還想學到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI