首页 > web前端 > js教程 > 正文

js中根据json生成html表格的方法介绍(代码)

不言
发布: 2018-10-24 11:40:34
转载
3975人浏览过

本篇文章给大家带来的内容是关于js中根据json生成html表格的方法介绍(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

之前公司有一个需求是:通过js来生成html。而且大部分都是生成表格,直接通过字符串拼接的话,代码的可复用性太低的,所以写了个通用的json转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是创建html标签的工具

函数

函数名 作用 例子
start (tag, attrs) 创建未封闭标签头 start("table", {"cellpadding": "10", "border": "1"}),输出
end () 创建上一个start函数的标签尾 上面执行了start("table"),再执行end(),输出
tag (tag, attr, text) 创建封闭标签 tag("th", {"bgcolor": "AntiqueWhite"}, "hello"),输出 hello

json2Html

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

var html = json2Html(htmlMetadata);

console.info(html);
登录后复制

输出结果(结果为了好看,格式化了):

<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>
登录后复制

效果:

语文 数学 英语
80 89 90
合计 259

以上就是js中根据json生成html表格的方法介绍(代码)的详细内容,更多请关注php中文网其它相关文章!

HTML速学教程(入门课程)
HTML速学教程(入门课程)

HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!

下载
相关标签:
来源:segmentfault思否网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号