[JavaScript]根据json生成html表格

news/2024/7/1 21:15:52

之前公司有一个需求是:通过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));
        return this;
    }, end: function () {
        this.html.push(this._createTag(this._tags.pop(), null, false));
        return this;
    }, tag: function (tag, attr, text) {
        this.html.push(this._createTag(tag, attr, true) + text + this._createTag(tag, null, false));
        return this;
    },
    create: function () {
        var t = this.html.join("");
        this.clear();
        return t;
    },
    clear: function () {
        this._tags = [];
        this.html = [];
    }
};

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"}),输出<table cellpadding="10" border="1">
end ()创建上一个start函数的标签尾上面执行了start("table"),再执行end(),输出</table>
tag (tag, attr, text)创建封闭标签 tag("th", {"bgcolor": "AntiqueWhite"}, "hello"),输出<th bgcolor="AntiqueWhite">hello</th>

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>

效果:

语文数学英语
808990
合计259
文中若存在错误或有更好的方法,恳请指出,谢谢。

http://www.niftyadmin.cn/n/2037907.html

相关文章

Algs4-1.3.23为什么下面的代码和1.3.22效果不同

1.3.23为什么下面这段代码和上一道题中的代码效果不同&#xff1f;x.nextt;t.nextx.next;答&#xff1a;第二行时x.next指向t,而t.nextx.next&#xff0c;说明t.next提向了t。转载于:https://www.cnblogs.com/longjin2018/p/9849546.html

.Net 如何访问主流的各大数据库

做过开发的都知道&#xff0c;.NET基本可以理解是和MSSQL&#xff0c;windows服务器属于一个好的搭档&#xff0c;正如PHP和MYSQL&#xff0c;LIUNX等也可以理解是一个完美搭配&#xff1b;但是在实际的开发中并不完全是这样的&#xff0c;如果你是学.NET 开发&#xff0c;再有…

Qt菜单栏、工具栏和状态栏

Qt菜单栏、工具栏和状态栏菜单栏菜单栏类QMenuBar动作类QAction菜单类QMenu右键菜单工具栏状态栏菜单栏 两种菜单&#xff1a; 程序界面顶端&#xff0c;鼠标左键单击。界面右击&#xff0c;弹出上下文菜单&#xff0c;右键菜单。 菜单栏类QMenuBar&#xff0c;添加QMenu和Q…

VS Code 快捷键(中英文对照版)

原文地址 https://segmentfault.com/u/soulman 希望可以帮到您

《Rust权威指南》学习笔记之第8章 通用集合类型

《Rust权威指南》学习笔记之第8章 通用集合类型动态数组创建更新销毁读取动态数组中的元素遍历枚举存储多个类型值字符串存储UTF-8文本字符串是什么创建新字符串更新字符串字符串索引内部布局字符串切片遍历字符串哈希映射中存储键值对创建哈希映射哈希映射与所有权访问哈希映射…

进程占用情况记录

使用一下命令查使用内存最多的3个进程 ps -aux | sort -k4nr | head -K 说明&#xff1a; 如果是10个进程&#xff0c;K10&#xff0c;如果是最高的三个&#xff0c;K3 说明&#xff1a;ps -aux中&#xff08;a指代all——所有的进程&#xff0c;u指代userid——执行该进程的用…

《Rust权威指南》学习笔记之第9章 错误处理

《Rust权威指南》学习笔记之第9章 错误处理不可恢复错误与panic!panic!中产生回溯信息可恢复错误与Result匹配不同错误失败时触发panic的快捷方式&#xff1a;unwrap和expect传播错误传播错误的快捷方式&#xff1a;&#xff1f;运算符?运算符只能被用于返回Result的函数要不要…

P2018 消息传递

暴力贪心即可. 考虑从下往上计算. 对于一个根节点的所有子节点, 明显我们应该优先告诉耗时长的子节点. 于是贪心. 假设已经知道了所有子节点的最少花费时间. 我们将其从小到大排序, 那么最后一个应该最先告诉.这可以通过交换法证明. 当前节点的最小花费也就可以构造出来了. #in…