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 相关文章推荐
jQuery live
May 15 Javascript
jquery实现的带缩略图的焦点图片切换(自动播放/响应鼠标动作)
Jan 23 Javascript
js实现获取div坐标的方法
Nov 16 Javascript
jquery实现左右无缝轮播图
Jul 31 Javascript
AngularJS实现按钮提示与点击变色效果
Sep 07 Javascript
基于jPlayer三分屏的制作方法
Dec 21 Javascript
angular2组件中定时刷新并清除定时器的实例讲解
Aug 31 Javascript
javascript动态创建对象的属性详解
Nov 07 Javascript
webpack中如何加载静态文件的方法步骤
May 18 Javascript
Vue使用NProgress的操作过程解析
Oct 10 Javascript
Vue.js获取手机系统型号、版本、浏览器类型的示例代码
May 10 Javascript
ant-design-vue 时间选择器赋值默认时间的操作
Oct 27 Javascript
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 文件缓存的性能测试
2010/04/25 PHP
PHP实现的redis主从数据库状态检测功能示例
2017/07/20 PHP
PHP5.6新增加的可变函数参数用法分析
2017/08/25 PHP
实例分析基于PHP微信网页获取用户信息
2017/11/24 PHP
犀利的js 函数集合
2009/06/11 Javascript
基于JQuery的密码强度验证代码
2010/03/01 Javascript
js arguments,jcallee caller用法总结
2013/11/30 Javascript
node.js中的fs.rmdirSync方法使用说明
2014/12/16 Javascript
JavaScript中常用的六种互动方法示例
2015/03/13 Javascript
如何使用AngularJs打造权限管理系统【简易型】
2016/05/09 Javascript
浅谈js里面的InttoStr和StrtoInt
2016/06/14 Javascript
jQuery展示表格点击变色、全选、删除
2017/01/05 Javascript
JavaScript定义全局对象的方法示例
2017/01/12 Javascript
jQuery.form.js的使用详解
2017/06/14 jQuery
Javascript实现找不同色块的游戏
2017/07/17 Javascript
JS函数节流和函数防抖问题分析
2017/12/18 Javascript
vue 解决循环引用组件报错的问题
2018/09/06 Javascript
Vue简单实现原理详解
2020/05/07 Javascript
python的几种开发工具介绍
2007/03/07 Python
解决pandas 作图无法显示中文的问题
2018/05/24 Python
DES加密解密算法之python实现版(图文并茂)
2018/12/06 Python
Apache,wsgi,django 程序部署配置方法详解
2019/07/01 Python
pytorch进行上采样的种类实例
2020/02/18 Python
Python将字典转换为XML的方法
2020/08/01 Python
Python实现LR1文法的完整实例代码
2020/10/25 Python
matplotlib制作雷达图报错ValueError的实现
2021/01/05 Python
一款纯css3实现的竖形二级导航的实例教程
2014/12/11 HTML / CSS
详解CSS3原生支持div铺满浏览器的方法
2018/08/30 HTML / CSS
英国领先的新鲜松露和最好的松露产品供应商:TruffleHunter
2019/08/26 全球购物
写给老师的表扬信
2014/01/21 职场文书
餐饮营销方案
2014/02/23 职场文书
优秀语文教师事迹
2014/05/18 职场文书
教育系统干部作风整顿心得体会
2014/09/09 职场文书
上诉状格式
2015/05/23 职场文书
导游词之寿县报恩寺
2020/01/19 职场文书
Redis安装使用RedisJSON模块的方法
2022/03/23 Redis