2011-10-12 23 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>標籤

相關問題