JavaScript根据json生成html表格的示例代码


Posted in Javascript onOctober 24, 2018

之前公司有一个需求是:通过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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
JavaScript 32位整型无符号操作示例
Dec 08 Javascript
jquery和雅虎的yql服务实现天气预报服务示例
Feb 08 Javascript
jQuery toggleClass应用实例(附效果图)
Apr 06 Javascript
js去除输入框中所有的空格和禁止输入空格的方法
Jun 09 Javascript
手机端转盘抽奖代码分享
Sep 10 Javascript
用JS生成UUID的方法实例
Mar 30 Javascript
AngularJS变量及过滤器Filter用法分析
Nov 22 Javascript
vue动态生成dom并且自动绑定事件
Apr 19 Javascript
vue-cli项目中使用echarts图表实例
Oct 22 Javascript
原生JS实现的跳一跳小游戏完整实例
Jan 27 Javascript
原生js实现的移动端可拖动进度条插件功能详解
Aug 15 Javascript
Vue中插槽slot的使用方法与应用场景详析
Jun 08 Vue.js
vue项目引入Iconfont图标库的教程图解
Oct 24 #Javascript
vue中的router-view组件的使用教程
Oct 23 #Javascript
jQuery pagination分页示例详解
Oct 23 #jQuery
jquery.pagination.js分页使用教程
Oct 23 #jQuery
vue项目使用微信公众号支付总结及遇到的坑
Oct 23 #Javascript
jquery分页插件pagination使用教程
Oct 23 #jQuery
使用 electron 实现类似新版 QQ 的登录界面效果(阴影、背景动画、窗体3D翻转)
Oct 23 #Javascript
You might like
php中使用Ajax时出现Error(c00ce56e)的详细解决方案
2014/11/03 PHP
php实现的用户查询类实例
2015/06/18 PHP
CI框架实现优化文件上传及多文件上传的方法
2017/01/04 PHP
使用SyntaxHighlighter实现HTML高亮显示代码的方法
2010/02/04 Javascript
js读取本地excel文档数据的代码
2010/11/11 Javascript
jquery.fileEveryWhere.js 一个跨浏览器的file显示插件
2011/10/24 Javascript
使用Jquery来实现可以输入值的下拉选单 雏型
2011/12/06 Javascript
Javascript 加载和执行-性能提高篇
2012/12/28 Javascript
jQuery中setTimeout的几种使用方法小结
2013/04/07 Javascript
浅析AngularJS中的指令
2016/03/20 Javascript
基于Node.js的JavaScript项目构建工具gulp的使用教程
2016/05/20 Javascript
关于Function中的bind()示例详解
2016/12/02 Javascript
基于JavaScript实现百度搜索框效果
2020/06/28 Javascript
解决angular2 获取到的数据无法实时更新的问题
2018/08/31 Javascript
微信小程序中悬浮窗功能的实现代码
2019/08/02 Javascript
easyUI 实现的后台分页与前台显示功能示例
2020/06/01 Javascript
python 定时修改数据库的示例代码
2018/04/08 Python
Python 使用 PyMysql、DBUtils 创建连接池提升性能
2019/08/14 Python
Python实现基于socket的udp传输与接收功能详解
2019/11/15 Python
python实现可下载音乐的音乐播放器
2020/02/25 Python
通过python调用adb命令对App进行性能测试方式
2020/04/23 Python
Jupyter安装链接aconda实现过程图解
2020/11/02 Python
HTML5开发动态音频图的实现
2020/07/02 HTML / CSS
领先的钻石和订婚戒指零售商:Diamonds-USA
2016/12/11 全球购物
Fossil德国官网:化石手表、手袋、珠宝及配件
2019/12/07 全球购物
2014年三八妇女节活动总结
2014/03/01 职场文书
企业文化建设实施方案
2014/03/22 职场文书
十佳中学生事迹材料
2014/06/02 职场文书
大班亲子运动会方案
2014/06/10 职场文书
学籍证明模板
2014/11/21 职场文书
2014年图书室工作总结
2014/12/09 职场文书
医院科室评语
2015/01/04 职场文书
小学少先队活动总结
2015/05/08 职场文书
火烧圆明园的观后感
2015/06/03 职场文书
《秦兵马俑》教学反思
2016/02/24 职场文书
安装Windows Server 2012 R2企业版操作系统并设置好相关参数
2022/04/29 Servers