2013-07-31 115 views
2

我有一個HTML表:如何使用jquery刪除HTML TABLE中的最後一列?

<table id="persons" border="1"> 
    <thead id="theadID"> 
     <tr> 
      <th>Name</th> 
      <th>sex</th> 
      <th>Message</th> 
     </tr> 
    </thead> 
    <tbody id="tbodyID"> 
     <tr> 
      <td>Viktor</td> 
      <td>Male</td> 
      <td>etc</td> 
     </tr> 
     <tr> 
      <td>Melissa</td> 
      <td>Female</td> 
      <td>etc</td> 
     </tr> 
     <tr> 
      <td>Joe</td> 
      <td>Male</td> 
      <td>etc</td> 
     </tr> 
    </tbody> 
</table> 
<input type="button" onclick="deleteLastColumn();" value="do it"/> 

我需要一個JavaScript/jQuery代碼,它刪除表中的最後一列(消息):

function deleteLastColumn() { 
    $("#theadID tr th:not(:last-child)...... 
    $("#tbodyID tr td:not(:last-child)...... 
} 

所以結果應該是這樣的:

<table id="persons" border="1"> 
    <thead id="theadID"> 
     <tr> 
      <th>Name</th> 
      <th>sex</th> 
     </tr> 
    </thead> 
    <tbody id="tbodyID"> 
     <tr> 
      <td>Viktor</td> 
      <td>Male</td> 
     </tr> 
     <tr> 
      <td>Melissa</td> 
      <td>Female</td> 
     </tr> 
     <tr> 
      <td>Joe</td> 
      <td>Male</td> 
     </tr> 
    </tbody> 
</table> 

我知道有「:not(last)」方法,但我找不到任何示例來解決我的問題。 任何人都可以幫助我嗎?

回答

9

嘗試

$('#persons tr').find('th:last-child, td:last-child').remove() 

演示:Fiddle

+0

作品!謝謝! – victorio

1

除了阿倫P佐尼的回答,

,將讓你每一次刪除最後一行單擊該按鈕。如果你只是想刪除一列,而不是其他人,你可以試試這個。

function deleteLastColumn() { 
    $(document).find('.last').remove() 
} 

加入last類到最後td和表的th後。

演示:Fiddle

相關問題