2013-08-24 41 views
0

當我嘗試刪除第一行它的工作原理,但我添加更多的行我不能刪除它們。出於某種原因,我只能刪除第一行。動態刪除行不會工作,只刪除第一行而不刪除其他人

這裏是我的html

<table class="pretty property_units" style="width:800px;"> 
<thead> 
<tr> 
<th>Bedroom</th> 
<th>Bathroom</th> 
<th>Square Feet</th> 
<th>Price</th> 
<th>Available</th> 
<th>Action</th> 
</tr> 
</thead> 
<tbody> 
<tr class="rows"> 
    <td><input type='text' name='bedroom[]' value='0' class='input-small'></td> 
    <td><input type='text' name='bath[]' value='0' class='input-small'></td> 
    <td><input type='text' name='sqrt[]' value='0' class='input-small'></td> 
    <td><input type='text' name='price[]' value='0' class='input-small'></td> 
    <td> 
     <select name='avail[]' class='input-small'> 
     <option value='yes'>Yes</option> 
     <option value='no'>No</option> 
     </select> 
    </td> 
    <td><button type="button" class="btn btn-danger btn-small removeRow">remove</button></td> 
</tr> 
</tbody> 
</table> 
<button type="button" class="btn btn-small btn-primary addrow">add row</button> 

,這裏是我的js

<script type="text/javascript"> 
$(document).ready(function() { 
    $(".addrow").click(function() { 
     var tblrow = $('table.property_units tr.rows:last').clone(); 
     $("table.property_units tbody").append(tblrow); 
    }); 

    $(".removeRow").click(function() { 
     $(this).closest("tr").remove(); 
     return false; 
    }); 
}); 
</script> 
+0

可能重複的[jQuery的如何onclick事件綁定到動態添加HTML元素(http://stackoverflow.com/questions/1525664/jquery-how-to-bind-on-click-event-to-dynamic-added-html-element) – Barmar

+0

我已經看到你列出的示例,但它不是很清楚。我的例子對讀者非常清楚,代碼非常清晰,乾淨。 –

+0

如果這個問題不清楚,也許與其相關的許多問題之一。這個問題每天都會被問到,其中一個問題應該有你理解的答案。 – Barmar

回答

2

你必須委派事件:

$(document).on('click', '.removeRow', function() { 
    $(this).closest("tr").remove(); 
    return false; 
}); 

爲了提高性能,我想補充一個ID,表和事件綁定表中,而不是document

詳細解釋have a look at this question

+0

感謝您的回答,所以用$(document)而不是$('。removeRow')它等待事件發生? –

+0

$()。click和$()。on('click')之間的區別是什麼 –

+0

它基本上將click事件添加到'document'並檢查實際單擊元素是否是'.removeRow'。如果將它直接綁定到'.removeRow',新創建的元素將不會有任何事件處理程序。 'click'只是on('click')的簡短版本,''on'允許你添加一個委託參數。 –

0

當您創建新的元素與jQuery你必須綁定一個事件。您可以使用委託,而不是點擊,點擊這裏: enter link description here

也可以使功能deleteRws(){你的刪除代碼} 再經過調用它。 $(「table.property_units TBODY」)追加( tblrow);

+0

謝謝我會閱讀它 –

0

$(".removeRow").click(...只適用於在調用時存在的任何匹配行。它不會影響通過您的.addrow點擊處理程序創建的新行(及其內容)。

您需要手動添加:

$(document).ready(function() { 
    var remover = function() { 
    $(this).closest("tr").remove(); 
    return false; 
    }; 

    $(".addrow").click(function() { 
      var tblrow = $('table.property_units tr.rows:last').clone(); 
      $('.removeRow', tblrow).click(remover); 
      $("table.property_units tbody").append(tblrow); 
     }); 

    $(".removeRow").click(remover); 
}); 

實施例:http://codepen.io/paulroub/pen/Bekit

+0

我從來不知道你可以這樣做,$('。removeRow',tblrow) –