2011-10-12 54 views
5

我有一个HTML表格,我想使用一些基本的JavaScript选择框来动态添加或删除行。HTML - 是否有正确的容器元素放置在表格行周围?

我没有添加单行,而是同时添加了一组相似的行。例如,如果我已经有一个组,然后增加了另一个,结果会喜欢这样:

<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的克隆方法,所以我需要某种容器元素的去但是,我试过的所有东西(span,div等)都导致HTML无效,并且无法正确运行。

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

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

+0

你必须在你行的容器? 'tr'应该足够了。否则,你可能会想为每一行和每列创建'div'。 – skyuzo

回答

4

能使用tbody。你尝试过吗?

8

<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> 

注意到,该表中,您必须将所有<tr> s放在<tbody>(或<thead><tfoot>)元素中,或者全部不填。

I.e.这是有效的:

<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> 
+4

+1我不知道'tbody'元素可以在表格中多次使用 – jasonscript

+0

@jasonscript:heck yes。并且''创建一个标题的单元格,标记其父''元素。 –

0

你可以尝试<tbody>标签

相关问题