2010-01-29 38 views
13

我有一個表中的HTML如下如何在jQuery中從表中刪除當前行?

<table> 
<tbody> 
<tr> 
<td>test content</td> 
<td><input type="button" onClick="remove()"></td> 
</tr> 
.... 
... 

</tbody> 
</table> 

現在如果同樣的模式繼續下去,我想如果一個刪除按鈕,點擊該行以刪除行。我如何實現與jQuery相同?

回答

48

一些好的:

$(this).closest('tr').remove(); 

More on closest()

<input type="button" onClick="$(this).closest('tr').remove();"> 

無論您的HTML在單元格中顯示的樣子如何,這都有益於工作。

+0

酷... :)謝謝 – Amit 2010-01-29 13:22:01

6

試試這個:

<input type="button" onClick="$(this).parent().parent().remove();"> 

或者你可以使它更通用的是這樣的:

<script> 
    $(document).ready(function() 
    { 
    $(".btn").click(function(){ 
     $(this).parent().parent().remove(); 
    }); 
    }); 
</script> 

<tr> 
    <td><input type="button" class="btn"></td> 
</tr> 
+0

雖然可能想使用類而不是id。 – 2010-01-29 13:13:43

+0

@Sam Hasler:同意並修復,謝謝你通知:) – Sarfraz 2010-01-29 13:18:19

+0

如果他想刪除該行,我會在你的代碼中包含一個'tr',以防他添加了像div這樣的元素。然後你的代碼會中斷,但@ alt的代碼不會。 – Martin 2010-01-29 13:21:14