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 监听textarea中按键事件
Oct 08 Javascript
Jquery下判断Id是否存在的代码
Jan 06 Javascript
JavaScript字符串插入、删除、替换函数使用示例
Jul 25 Javascript
JQuery操作textarea,input,select,checkbox方法
Sep 02 Javascript
jQuery模仿单选按钮选中效果
Jun 24 Javascript
js实现图片左右滚动效果
Feb 27 Javascript
vue自定义底部导航栏Tabbar的实现代码
Sep 03 Javascript
webpack+vue-cli项目中引入外部非模块格式js的方法
Sep 28 Javascript
微信小程序保存多张图片的实现方法
Mar 05 Javascript
vue实现将数据存入vuex中以及从vuex中取出数据
Nov 08 Javascript
vue实现图片上传功能
May 28 Javascript
Jquery高级应用Deferred对象原理及使用实例
May 28 jQuery
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远程连接MYSQL数据库非常慢的解决方法
2008/07/05 PHP
鸡肋的PHP单例模式应用详解
2013/06/03 PHP
PHP有序表查找之二分查找(折半查找)算法示例
2018/02/09 PHP
BOOM vs RR BO3 第一场2.13
2021/03/10 DOTA
ExtJS Window 最小化的一种方法
2009/11/18 Javascript
javascript 原型继承介绍
2011/08/30 Javascript
jQuery点击tr实现checkbox选中的方法
2013/03/19 Javascript
DIV+CSS+JS不间断横向滚动实现代码
2013/03/19 Javascript
jQuery中:hidden选择器用法实例
2014/12/30 Javascript
javascript实现链接单选效果的方法
2015/05/13 Javascript
jQuery实现点击小图片淡入淡出显示大图片特效
2015/09/09 Javascript
JavaScript动态设置div的样式的方法
2015/12/26 Javascript
javascript中this指向详解
2016/04/23 Javascript
js验证框架之RealyEasy验证详解
2016/06/08 Javascript
jquery dataTable 后台加载数据并分页实例代码
2017/06/07 jQuery
JS实现基于Sketch.js模拟成群游动的蝌蚪运动动画效果【附demo源码下载】
2017/08/18 Javascript
vue.js系列中的vue-fontawesome使用
2018/02/10 Javascript
详解node.js 下载图片的 2 种方式
2018/03/02 Javascript
详解webpack4多入口、多页面项目构建案例
2018/05/25 Javascript
vue非父子组件通信问题及解决方法
2018/06/11 Javascript
使用Vue中 v-for循环列表控制按钮隐藏显示功能
2019/04/23 Javascript
Vue中使用better-scroll实现轮播图组件
2020/03/07 Javascript
vue 使用rules对表单字段进行校验的步骤
2020/12/25 Vue.js
[15:46]教你分分钟做大人——沙王
2015/03/11 DOTA
Python实现的生成自我描述脚本分享(很有意思的程序)
2014/07/18 Python
python使用PyGame绘制图像并保存为图片文件的方法
2015/04/24 Python
python中argparse模块用法实例详解
2015/06/03 Python
Python中生成Epoch的方法
2017/04/26 Python
python实现类之间的方法互相调用
2018/04/29 Python
使用html5+css3来实现slider切换效果告别javascript+css
2013/01/08 HTML / CSS
AmazeUI 缩略图的实现示例
2020/08/18 HTML / CSS
员工廉洁自律承诺书
2014/05/26 职场文书
知识就是力量演讲稿
2014/09/13 职场文书
费用申请报告范文
2015/05/15 职场文书
python - asyncio异步编程
2021/04/06 Python
Django框架中表单的用法
2022/06/10 Python