使用rowspan和循环动态生成包含子表的表

时间:2017-11-14 08:18:32

标签: html html-table

我需要下表结构的html表。

Table

这是我迄今为止尝试过的类似内容:(这是一个.cshtml视图,它以模型作为输入)

    <table>
        <tbody>
            <tr>
                <th>Code Number of Equipment</th>
                <th>Name of Equipment</th>
                <th>Brand</th>
                <th>Model</th>
                <th>Quantity</th>

                <th>Check Item</th>
                <th>Note</th>
                <th>Quoted Price</th>
            </tr>
            @foreach (var equipment in Model.Equipments)
            {
                <tr>
                    <td>@equipment.Code</td>
                    <td>@equipment.Name</td>
                    <td>@equipment.EquipmentBrand</td>
                    <td>@equipment.EquipmentModel</td>
                    <td>@String.Format("{0:n0}", equipment.Quantity)</td>
                    <td colspan="2">
                        <table >
                            <tbody >
                                @foreach (var item in equipment.EligibilityChecksheets)
                                {
                                    <tr>
                                        <td>@item.CheckListItem</td>
                                        <td>@item.Note</td>
                                    </tr>
                                }
                            </tbody>
                        </table>
                    </td>
                    <td>@String.Format("{0:n0}", Model.Currency + " " + equipment.UnitPrice)</td>
                </tr>
            }
            <tr>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th>Total : </th>
                <th>@String.Format("{0:n0}", Model.Currency + " " + Model.TotalPrice)</th>
            </tr>
        </tbody>
    </table>

此代码的问题是 - <td>与内部表之间存在差距。我想使用rowspan来完成这项工作 - 是否可以针对这种情况进行此操作?

1 个答案:

答案 0 :(得分:1)

创建HTML表时,表的表行按HTML顺序构造;即 - 一旦您创建了新的<tr>,就无法直接从HTML中添加新的<td>或其他表格元素。

出于这个原因,这种方法的任何变体都不会像您期望的那样工作:

<tr>

我能想到的有关你如何做你要求的事情的一件事是 - 完全构造第一行 - 包括子表的第一行。构造该行之后,您可以为该特定父表行构造子表的其余行。

在代码中,方法将是这样的(考虑<table> foreach(parent-row in parent-table) { <tr> <!-- parent table data of each row in "td"s with rowspan --> foreach(child-row in child-table) { <tr> <!-- child table data of each row in "td"s without rowspan --> </tr> } <!-- remaining parent table data of each row in "td"s with rowspan --> </tr> } </table> ):

rowspan = 'number of rows in child table for a particular row in the parent table'