>  기사  >  웹 프론트엔드  >  js에서 json을 기반으로 html 테이블을 생성하는 방법 소개(코드)

js에서 json을 기반으로 html 테이블을 생성하는 방법 소개(코드)

不言
不言앞으로
2018-10-24 11:40:343733검색

이 글은 js에서 json을 기반으로 html 테이블을 생성하는 방법(코드)을 소개합니다. 필요한 친구들이 참고할 수 있기를 바랍니다.

이전에는 회사에서 js를 통해 html을 생성해야 한다는 요구 사항이 있었습니다. 그리고 대부분 테이블을 생성하는데, 문자열을 직접 연결하면 코드의 재사용성이 너무 낮아서 일반 json to html 테이블 도구를 작성했습니다.

Code

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 태그를 생성하는 도구입니다.

Function

end ()</table>

이전 시작 함수의 end 태그를 생성합니다위에서는 start("table")를 실행한 다음, end() 실행, 출력</table>

tag(tag, attr, text)

닫힌 태그 만들기

tag("th", {"bgcolor ": "AntiqueWhite" }, "hello"), <th bgcolor="AntiqueWhite">hello</th>

함수 이름 Function
시작( tag, attrs) 닫히지 않은 태그 헤더 만들기 start("table", {"cellpadding": "10", "border": "1"}), 출력 &lt ;table cellpadding="10" border="1">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>
json2Html 예 :
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>
중국어수학English </table>
80

89🎜 🎜 90🎜🎜🎜🎜 합계🎜🎜259🎜🎜🎜🎜🎜🎜🎜

위 내용은 js에서 json을 기반으로 html 테이블을 생성하는 방법 소개(코드)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 segmentfault.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제
이전 기사:
json 출력 to Html
효과: