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

Dan*_*Dan 5 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>
Run Code Online (Sandbox Code Playgroud)

要添加行,我使用的是jQuery的clone方法,所以我需要某种容器元素来绕过行组,但是,我尝试的所有内容(span,div等)导致HTML无效并且无法正常运行.

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

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

Pau*_*ite 10

<tbody> 是你要找的标签.

(如果你的<th>s是他们的表行组的标题,你也可以使用该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>
Run Code Online (Sandbox Code Playgroud)

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

即这是有效的:

<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>
Run Code Online (Sandbox Code Playgroud)

但这不是:

<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>
Run Code Online (Sandbox Code Playgroud)

  • +1我不知道`tbody`元素可以在表格中多次使用 (4认同)

Ed *_*eal 6

可以用tbody。你试过吗?