2013-01-23 31 views
0

可能重複:
Jquery adding event listeners to dynamically added elementsjQuery的:一個生成的按鈕不趕上click事件

jQuery的位:

我追加輸入字段的一些文本到DIV :

 shareVisual = '<div class="individual-share">' + '<input type="number" value="1" /> X ' + classname.val() + '@' + classcurrency.val() + ' ' + classprice.val() + ' per share ' + '<button type="button" class="remove-share">Remove</button></div>'; 
     listOfSharesBox.append(shareVisual); 

然後我嘗試去捕捉點擊事件:

$("#list-of-shares").bind('click', '.remove-share', function() { 
    $(".remove-share").closest("div").find(".individual-share").remove(); 
}); 

爲什麼DIV不會被刪除?

乾杯。

P.S.

當我改變我的代碼如下:

$("#list-of-shares").bind('click', '.remove-share', function() { 
    $(".remove-share").closest("div").remove(); 
}); 

的所有動態生成的投入得到專區內刪除。

+2

使用'on'方法http://api.jquery.com/on/ – undefined

回答

2

如果您使用的jQuery 1.7手段嘗試這樣

$(".remove-share").on('click',function() { 
    $(this).closest("div").remove(); 
}); 

以其它方式使用

$(".remove-share").bind('click',function() { 
    $(this).closest("div").remove(); 
}); 
+0

我改變了代碼,現在我有這個: $(listOfSharesBox).bind('click','remove-share',function(){(this).closest(「div」)。find(「。individual-share」)。remove(); }); 不幸的是,當我點擊一個按鈕,它會刪除父div內的所有DIV。我想要的只是刪除一個帶有與之相關聯的按鈕的div。 – chuckfinley

+0

no yuo不應該有這樣的$(listOfSharesBox),因爲listOfSharesBox是一個變量而不是dom對象 – muthu

-1

嘗試使用 '活' 的關鍵字與動態生成控件科佩斯:

$(".remove-share").live('click', function() { 
$(this).closest("div").remove(); 
}); 
+1

'live'已被棄用。您應該使用'on' –

相關問題