项目中有需求根据返回的数据生成表格并合并单元格,今天记录下。

dom结构如下:

<table id="mytable">
        <thead>
            <tr>
                <th>兑换商品</th>
                <th>姓名</th>
                <th>工号</th>
                <th>兑换数量</th>
                <th>合计</th>
            </tr>
        </thead>
        <tbody id="mytbody">
        </tbody>
</table>

js代码如下:

var tableJson = {
    "tableList":[
        {
            "goods":"电影券",
            "userList":[
                {
                    "name":"张三",
                    "wordNum":"123",
                    "exchangeNum":"3"
                },{
                    "name":"李四",
                    "wordNum":"456",
                    "exchangeNum":"6"
                },{
                    "name":"王五",
                    "wordNum":"789",
                    "exchangeNum":"9"
                }
            ],
            "total":"18"
        },{
            "goods":"购物券",
            "userList":[
                {
                    "name":"张三",
                    "wordNum":"123",
                    "exchangeNum":"1"
                },{
                    "name":"李四",
                    "wordNum":"456",
                    "exchangeNum":"4"
                },{
                    "name":"王五",
                    "wordNum":"789",
                    "exchangeNum":"7"
                }
            ],
            "total":"12"
        }
    ]
};
var getTbodyHtml = function(data){
    var tbodyHtml = '';
    for(var i=0;i<data.length;i++){
        for(var j=0;j<data[i].userList.length;j++){
            if(j == 0){
                tbodyHtml += "<tr><td rowspan="+data[i].userList.length+">"+data[i].goods+"</td><td>"+data[i].userList[j].name+"</td><td>"+data[i].userList[j].wordNum+"</td><td>"+data[i].userList[j].exchangeNum+"</td><td rowspan="+data[i].userList.length+">"+data[i].total+"</td></tr>";
            }else{
                tbodyHtml += "<tr><td>"+data[i].userList[j].name+"</td><td>"+data[i].userList[j].wordNum+"</td><td>"+data[i].userList[j].exchangeNum+"</td></tr>";
            }
        }
    };
    return tbodyHtml;
};

document.getElementById('mytbody').innerHTML = getTbodyHtml(tableJson.tableList);

效果如下图:

如有表述不准确之处,欢迎指正,欢迎补充,感谢阅读。