2011-11-11 112 views
2

我有一個有4列的表,其中有一列有一個按鈕。我希望當按鈕收到點擊按鈕將被排除在外的表格行。JQuery表/按鈕刪除

由於表格行是通過單擊另一個按鈕動態插入的,因此按鈕的ID是動態的,這使得我無法使用表格中按鈕的ID作爲選擇器。

然後我會做下面的事情:在按鈕上單擊我想查找表中哪一行是按鈕,然後刪除這一行。

有什麼建議嗎?

我正在操作的表下方。

<table id="tbIngredients"> 
    <thead> 
      <tr> 
       <th id="cod"> Code </ th> 
       <th id="desc"> Description </ th> 
       <th id="price"> Price </ th> 
       <th id="op"> Operation </ th> 
      </ tr> 
    </ thead> 
    <tbody> 
      <tr> 
      <td id="tr1"> 1 </ td> 
      <td> Ingredient </ td> 
      <td> $ 1.00 </ td> 
      <td id="td1"> <input type="button" class="delIngredient" value="Excluir  ingrediente"> </ td> 
     </ tr> 
     <tr id="tr16"> 
      <td> 16 </ td> 
      <td> Papaya </ td> 
      <td> £ 01.05 </ td> 
      <td id="td16"> <input type="button" class="delIngredient" value="Excluir ingrediente"> </ td> 
     </ tr> 
    </ tbody> 
</ table>  

回答

2

怎麼樣,

$('.delIngredient').click(function(){ 
    $(this).parents('tr').remove(); 
}); 

錯過了動態的,如果你同時頁面加載後添加行,你需要將它添加到文檔,

$(document).on('click', '.delIngredient', function(){ 
    $(this).parents('tr').remove(); 
}); 
0
$('.delIngredient').click(function() { 
    $(this).parent().parent().remove(); 
}); 

將刪除父行。可能不是唯一的方法,但它適用於您的標記。

我想我更喜歡安德魯斯解決方案。然後它不依賴於嵌套。

0

試試這個:

$("#tbIngredients").on("click", ".delIngredient", function() { 
    $(this).closest("tr").remove(); 
}); 

DEMO