HTML - 表行周围是否有正确的容器元素?

时间:2011-10-12 10:58:26

标签: html html-table

我有一个HTML表格,我想使用带有一些基本javascript的选择框动态添加或删除行。

我不是在添加单行,而是同时添加一组相似的行。例如,如果我已经有一个集合,那么添加另一个集合,结果将是这样的:

<tr>
<th colspan="2">Item 1</th>
</tr>
<tr>
  <th>Title</th>
  <td>X</td>
</tr>
<tr>
  <th>Description</th>
  <td>Y</td>
</tr>
<tr>
<th colspan="2">Item 2</th>
</tr>
<tr>
  <th>Title</th>
  <td>A</td>
</tr>
<tr>
  <th>Description</th>
  <td>B</td>
</tr>

要添加行,我使用的是jQuery的clone方法,所以我需要某种容器元素来绕过行组,但是,我尝试过的所有内容(span,div等)都导致了无效的HTML和功能不正确。

我设法让它工作的唯一方法是将每个设置作为一个单独的表,但这不是我想要的效果。

我能做些什么来解决这个问题吗?

4 个答案:

答案 0 :(得分:10)

<tbody>是您正在寻找的标签。

(如果您的<th>是其表行组的标题,您还可以使用scope属性来表明:<th colspan="2" scope="rowgroup">。)

<tbody>
    <tr>
    <th scope="rowgroup" colspan="2">Item 1</th>
    </tr>
    <tr>
      <th scope="row">Title</th>
      <td>X</td>
    </tr>
    <tr>
      <th scope="row">Description</th>
      <td>Y</td>
    </tr>
</tbody>
<tbody>
    <tr>
    <th scope="rowgroup" colspan="2">Item 2</th>
    </tr>
    <tr>
      <th scope="row">Title</th>
      <td>A</td>
    </tr>
    <tr>
      <th scope="row">Description</th>
      <td>B</td>
    </tr>
</tbody>

但请注意,在表格中,您必须将所有<tr>放在<tbody>(或<thead><tfoot>)元素中,或者不放在任何元素中。< / p>

即。这是有效的:

<table>
    <!-- All <tr>s are inside <tbody>s -->
    <tbody>
        <tr>
            <td></td>
        </tr>
        <tr>
            <td></td>
        </tr>
    </tbody>
    <tbody>
        <tr>
            <td></td>
        </tr>
        <tr>
            <td></td>
        </tr>
    </tbody>
</table>

但这不是:

<table>
    <!-- <tr>s and <tbody>s can’t be siblings. -->
    <tr>
        <td></td>
    </tr>
    <tbody>
        <tr>
            <td></td>
        </tr>
        <tr>
            <td></td>
        </tr>
    </tbody>
</table>

答案 1 :(得分:4)

可以使用tbody。你试过了吗?

答案 2 :(得分:0)

答案 3 :(得分:0)

您可以尝试<tbody>代码