以前公司有一個需求是:經過js來生成html。並且大部分都是生成表格,直接經過字符串拼接的話,代碼的可複用性過低的,因此寫了個通用的json轉html表格的工具。javascript
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是建立html標籤的工具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> |
json轉Htmljava
例子:json
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 |