jquery 動態給table賦值

小魏的馬仔發表於2017-04-24

html

請忽視各種class,因為前端用的是layui

<table class="layui-table" lay-skin="line" id="datas">
    <colgroup>
        <col width="150">
        <col width="200">
        <col>
    </colgroup>
    <thead>
    <tr>
        <th>暱稱</th>
        <th>加入時間</th>
        <th>簽名</th>
    </tr>
    </thead>
    <tbody>
    <tr id="template">
        <td id="id"></td>
        <td id="url"></td>
        <td id="title"></td>
    </tr>
    </tbody>
</table>

js程式碼

<script>
    var data = [{
            "id": 1,
            "url": "http://www.jqcool.net",
            "switch": 1,
            "order": 1,
            "pid": 0,
            "title": "Online Program knowledge share and study platform"
        },
            {
                "id": 2,
                "url": "http://www.baidu.com",
                "switch": 0,
                "order": 2,
                "pid": 2,
                "title": "這是測試的數資料這是測試的數資料"
            },
            {
                "id": 3,
                "url": "http://www.taobao.com",
                "switch": 0,
                "order": 3,
                "pid": 2,
                "title": "淘寶購物"
            },
            {
                "id": 4,
                "url": "http://www.jqcool.net1",
                "switch": 1,
                "order": 4,
                "pid": 2,
                "title": "Online Program knowledge share and study platform2"
            },
            {
                "id": 5,
                "url": "http://www.baidu.com1",
                "switch": 0,
                "order": 5,
                "pid": 2,
                "title": "這是測試的數資料2"
            },
            {
                "id": 6,
                "url": "http://www.taobao.com1",
                "switch": 1,
                "order": 6,
                "pid": 0,
                "title": "淘寶購物2"
            }];
    $.each(data, function (i, n) {
        var row = $("#template").clone();
        row.find("#id").text(n.id);
        row.find("#url").text(n.url);
        row.find("#title").text(n.title);
        row.appendTo("#datas");//新增到模板的容器中
    });
</script>

效果

這裡寫圖片描述

相關文章