重慶分公司,新征程啟航
為企業提供網站建設、域名注冊、服務器等服務
為企業提供網站建設、域名注冊、服務器等服務
javascript中如何使用json生成html表格?相信很多新手小白還沒學會這個技能,通過這篇文章的總結,希望你能學會學會這個技能。以下資料是實現的步驟。
專注于為中小企業提供成都網站設計、成都網站建設服務,電腦端+手機端+微信端的三站合一,更高效的管理,為中小企業城西免費做網站提供優質的服務。我們立足成都,凝聚了一批互聯網行業人才,有力地推動了上千多家企業的穩健成長,幫助中小企業通過網站建設實現規模擴充和轉變。
之前公司有一個需求是:通過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"}) ,輸出
| |||
tag (tag, attr, text) | 創建封閉標簽 | tag("th", {"bgcolor": "AntiqueWhite"}, "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);
輸出結果(結果為了好看,格式化了):
語文 | 數學 | 英語 |
---|---|---|
80 | 89 | 90 |
合計 | 259 |
效果:
語文 | 數學 | 英語 |
---|---|---|
80 | 89 | 90 |
合計 | 259 |
看完這篇文章,你們學會javascript中使用json生成html表格的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注創新互聯行業資訊頻道,感謝各位的閱讀。