如何将表格单元格组合在一起,以便用一条语句隐藏它们?(网络表单)



我有一个表,第一行有两组单元格,每组包含5个单元格。每个单元格中都包含控件。

我的问题是,如果某个条件为真,我需要隐藏一个集并显示另一个集,反之亦然。目前,我的代码中有10个.Visible=语句用于true部分,10个用于false部分。有没有办法把一组单元格group放在一起,这样隐藏组就可以隐藏所有5个单元格?我必须在服务器端代码中完成这一切,而不是jQuery。

<table>
<tr>
<!-- first set -->
<td runat="server" id="set1_cell1"> content here</td>
<td runat="server" id="set1_cell2"> content here</td>
<td runat="server" id="set1_cell3"> content here</td>
<td runat="server" id="set1_cell4"> content here</td>
<td runat="server" id="set1_cell5"> content here</td>
<!-- end first set -->

<!-- second set -->
<td runat="server" id="set2_cell1"> content here</td>
<td runat="server" id="set2_cell2"> content here</td>
<td runat="server" id="set2_cell3"> content here</td>
<td runat="server" id="set2_cell4"> content here</td>
<td runat="server" id="set2_cell5"> content here</td>
<!-- end second set -->
</tr>
...
</table>

这就是我当前的代码看起来像的样子

if (condition is true)
{
 set1_cell1.Visible = true;
 set1_cell2.Visible = true;
 set1_cell3.Visible = true;
 set1_cell4.Visible = true;
 set1_cell5.Visible = true;
 set2_cell1.Visible = false;
 set2_cell2.Visible = false;
 set2_cell3.Visible = false;
 set2_cell4.Visible = false;
 set2_cell5.Visible = false;
}
else
{
  // opposite of the above
}

我想用一句话来代替这10句话。

您可以为每组的单元格指定不同的类名:

<table>
    <tr id="row1" runat="server">
        <td class="set1">Content 1a</td>
        <td class="set1">Content 1b</td>
        <td class="set1">Content 1c</td>
        <td class="set1">Content 1d</td>
        <td class="set1">Content 1e</td>
        <td class="set2">Content 2a</td>
        <td class="set2">Content 2b</td>
        <td class="set2">Content 2c</td>
        <td class="set2">Content 2d</td>
        <td class="set2">Content 2e</td>
        ...
    </tr>
    ...
</table>

在代码隐藏中,根据类名和条件值显示/隐藏单元格:

foreach (HtmlTableCell cell in row1.Cells)
{
    string className = cell.Attributes["class"];
    if (className == "set1")
    {
        cell.Visible = condition;
    }
    if (className == "set2")
    {
        cell.Visible = !condition;
    }
}

注意1:如果您愿意的话,类名也可以用于在客户端执行同样的操作(尤其是使用jQuery(。

注意2:我在上面的代码中使用了类名,但使用自定义属性(例如data-group="set1"而不是class="set1",代码后面有相应的更改(可以获得相同的结果。

最新更新