如何使用rowspan修复输出?

时间:2016-04-06 15:15:18

标签: javascript html html-table dynamic-tables

我正在创建动态表格,我希望显示如下内容:

Date               Time
               7:00 AM - 7:15 AM
               7:15 AM - 7:30 AM
03/16/2016     7:30 AM - 7:45 AM
               7:45 AM - 8:00 AM
               8:00 AM - 8:15 AM  

  Date               Time
               7:00 AM - 7:15 AM
               7:15 AM - 7:30 AM
05/05/2016     7:30 AM - 7:45 AM
               7:45 AM - 8:00 AM
               8:00 AM - 8:15 AM 

我得到的表看起来像这样:

  Date               Time

               7:15 AM - 7:30 AM
03/16/2016     7:30 AM - 7:45 AM
               7:45 AM - 8:00 AM
                   05/05/2016     7:00 AM - 7:15 AM
                                  7:15 AM - 7:30 AM
                                  7:30 AM - 7:45 AM
                                  7:45 AM - 8:00 AM
                                  8:00 AM - 8:15 AM 

这是我用来获取上面构建的表的代码:

function buildTbl(){
   var tbl = "<table><thead><tr><th>Date</th><th>Time</th></tr></thead>";
   tbl += "<tbody>";
   var count = 0;
   for (var i = 0; i < dates.length; i++) {
        var entries = groupedByDate[dates[i]];
        tbl+= "<tr><td rowspan='"+count+"'>"+dates[i]+"</td>";
        for (var j = 0; j < entries.length; j++) {
            tbl+="<td>"+entries[j].Slot_Label+"</td></tr>";
            count++;
        }
    }

    tbl += "</tbody></table>";
    $('#myTable').html(tbl);
}

我不确定我在哪个步骤中构建我的表html代码是错误的?我尝试在每次输出后切换并放置tr标签,但这并没有解决我的问题。如果有人看到我的代码有什么问题,请告诉我。谢谢。

2 个答案:

答案 0 :(得分:1)

rowspan的工作方式是它将从创建它的行向下扩展。在您的示例中,您希望启动创建新日期组的rowspan。

function buildTbl(){
   var tbl = "<table><thead><tr><th>Date</th><th>Time</th></tr></thead>";
   tbl += "<tbody>";
   for (var i = 0; i < dates.length; i++) {
        var entries = groupedByDate[dates[i]];
        var count = 0;
        for (var j in entries) {
            count++;
        }
        tbl+= "<tr>";
        tbl+= "<td rowspan='"+count+"' valign='middle'>"+dates[i]+"</td>";
        for (var j = 0; j < entries.length; j++) {
            if (j>0) {
                tbl+= "<tr>";               
            }
            tbl+="<td>"+entries[j].Slot_Label+"</td>";
            tbl+= "</tr>";      
            count++;
        }
    }

    tbl += "</tbody></table>";
    $('#myTable').html(tbl);
}

答案 1 :(得分:0)

你应该尝试:

tbl += "<tr><td rowspan='" + entries.length + "'>" + dates[i] + "</td>";