码农之路

js动态修改数据实现table相同行合并

2020-05-17  本文已影响0人  文心武士
原table未合并单元格
合并后table

完整示例代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <table border="1px">
            <thead>
                <tr>
                    <th>时间</th>
                    <th>课程</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </body>
    <script>
        //原始数据
        var list = [
            {time:'上午',course:'语文'},
            {time:'上午',course:'数学'},
            {time:'上午',course:'英语'},
            {time:'上午',course:'化学'},
            {time:'下午',course:'物理'},
            {time:'下午',course:'地理'},
            {time:'下午',course:'体育'},
            {time:'晚上',course:'自习'}
        ];
        //循环遍历
        for (var i = 0;i<list.length;i++) {
            //循环开始行
            var start_row ;
            //需合并的行数
            var rowspan = 1;
            //循环到最后一行时
            if(i==list.length-1){
                //如果最后一行和倒数第二行属性不同,则rowspan=1;否则直接结束循环
                if(list[i].time!=list[i-1].time){
                    list[i].rowspan = rowspan;
                }
                break;
            }
            //内层循环记录rowspan的数量
            for (var j = i;j<list.length-1;j++) {
                //记录循环结束的行数
                start_row=j;
                //属性相同则rowspan+1;否则直接结束内循环
                if(list[j].time==list[j+1].time){
                    rowspan ++;
                }else{                  
                    break;
                }
            }
            //为数组添加rowspan属性
            list[i].rowspan = rowspan;
            //控制外循环从内循环结束的行数开始
            i = start_row;
        }
        /* 
        处理完数据:
        list = [
                    {time: "上午", course: "语文", rowspan: 4},
                    {time: "上午", course: "数学"},
                    {time: "上午", course: "英语"},
                    {time: "上午", course: "化学"},
                    {time: "下午", course: "物理", rowspan: 3},
                    {time: "下午", course: "地理"},
                    {time: "下午", course: "体育"},
                    {time: "晚上", course: "自习", rowspan: 1}
                ]
        */
       
        //页面渲染
        var tbody = document.getElementsByTagName('tbody');
        var html = '';
        for (var i = 0;i<list.length;i++) {
            html += '<tr>';
            //动态添加rowspan属性
            if(list[i].rowspan != null){
                html += '<td rowspan = '+list[i].rowspan+'>'+list[i].time+'</td>';
            }
            html += '<td>'+list[i].course+'</td></tr>';
        }
        tbody[0].innerHTML = html;
    </script>
</html>

上一篇下一篇

猜你喜欢

热点阅读