Home > Web Front-end > JS Tutorial > Introduction to the method of generating html tables based on json in js (code)

Introduction to the method of generating html tables based on json in js (code)

不言
Release: 2018-10-24 11:40:34
forward
3829 people have browsed it

This article brings you an introduction to the method (code) of generating html tables based on json in js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Previously, the company had a requirement: to generate html through js. And most of them generate tables. If you directly splice strings, the reusability of the code is too low, so I wrote a general json to html table tool.

Code

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()
}
Copy after login

Instructions

HtmlKit

htmlKit is a tool for creating html tags

Function

##start (tag, attrs)Create an unclosed tag headertag (tag, attr, text)Create a closed tag
Function name Function Example
start("table", {"cellpadding": "10", "border": " 1"}), outputend ()Create the tag end of the previous start functionThe above executes start("table"), then executes end(), and outputs
tag("th", {"bgcolor": "AntiqueWhite"}, "hello" ), outputhello
##json2Html

json to Html

Example:

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": ["语文", "数学", "英语"],
    "dataKeys": [["chinese", "mathematics", "english"], ["text","1:2:total"]], // rowspan:colspan:value
    "data": [data, [{"text": "合计","total": total}]]
};

var html = json2Html(htmlMetadata);

console.info(html);
Copy after login

Output result (the result is formatted for better viewing):

<table cellpadding=10 border=1>
    <thead>
    <tr>
        <th bgcolor=AntiqueWhite>语文</th>
        <th bgcolor=AntiqueWhite>数学</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>
Copy after login

Effect:

Chinese##8089 90Total259##
Mathematics English

The above is the detailed content of Introduction to the method of generating html tables based on json in js (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Previous article:Introduction to the six attributes in the
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template