[英]jquery cloned button action not working
我有一個帶有添加/刪除按鈕的表,這些按鈕添加和刪除表中的行,每個新行也添加按鈕
這是我擁有的HTML
<table>
<tr>
<th>catalogue</th>
<th>date</th>
<th>add</th>
<th>remove</th>
</tr>
<- target row ->
<tr id="cat_row">
<td>something</td>
<td>something</td>
<td><input id="Add" type="button" value="Add" /></td>
<td><input id="Remove" type="button" value="Remove" /></td>
</tr>
</- target row ->
</table>
JavaScript:
$("#Add").click(function() {
$('#cat_row').after('<- target row with ->'); // this is only a notation to prevent repeatation
id++;
});
$("#Remove").click(function() {
$('#cat_'+id+'_row').remove();
id--;
});
請注意,每次添加新行后, id
也會更改,例如,單擊“添加”按鈕1次后,此處的id
也將更改
<table>
<tr>
<th>catalogue</th>
<th>date</th>
<th>add</th>
<th>remove</th>
</tr>
<tr id="cat_row">
<td>something</td>
<td>something</td>
<td><input id="Add" type="button" value="Add" /></td>
<td><input id="Remove" type="button" value="Remove" /></td>
</tr>
<tr id="cat_1_row">
<td>something</td>
<td>something</td>
<td><input id="Add" type="button" value="Add" /></td>
<td><input id="Remove" type="button" value="Remove" /></td>
</tr>
</table>
現在, 新添加的按鈕沒有動作,我必須始終單擊原始按鈕 -添加/刪除
在此之后,我想使“ 刪除按鈕” 僅 刪除單擊它的行,例如,如果我單擊第2行中的按鈕,則將刪除第2行
信息:我將python 2.7和web2py 2.2.1與jQuery的最新版本一起使用
您不能有兩個具有相同id
按鈕(您對“添加”和“刪除”都使用了重復的按鈕)。 id
值在頁面上必須唯一 。
您可能會考慮使用一個類,同時還會考慮事件委托。 例如,假設這是頁面上的唯一表(如果沒有,則只需使選擇器更具體),如果將按鈕更改為具有“ add-btn”和“ remove-btn”類而不是id
值,則您可以使用delegate
:
$("table").delegate(".add-btn", "click", function() {
// An add button was pressed, you can find out which
// row like this:
var row = $(this).closest('tr');
});
...以及類似的.remove-btn
按鈕。
或者,有些用戶更喜歡使用on
(請注意,參數的順序略有不同):
$("table").on("click", ".add-btn", function() {
// An add button was pressed, you can find out which
// row like this:
var row = $(this).closest('tr');
});
當前使用的是樣式問題。 為了清晰起見,我更喜歡使用delegate
,但是jQuery團隊喜歡超載其功能。 到目前為止,他們還沒有棄用delegate
,盡管他們確實稱其為“替代”。
我認為這會比以下更好:
$('#cat_'+id+_row').remove();
在您的onclick事件中執行此操作:
$(this).parent().parent().remove();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.