[英]Bind click event not work in dynamic created elements
我稱呼ajax,成功時我會建立按鈕元素。 像這樣 :
...
.done(function(data) {
$('#data-message').empty();
// console.log(data);
$('#total_notification_msg').html(data.total);
$.each(data.data, function(index, value) {
// console.log(value);
var redirectRead = '{{ route("adm1n.message.show", ":id") }}'
redirectRead = redirectRead.replace(":id", value.id);
var pesan = value.message.substr(0,100);
$('#data-message').append('<button id='reply' class='btn btn-default btn-xs' style='margin-top:5px;'>Reply</button>");
});
})
...
但是,我無法在#reply
按鈕上添加click事件。
我已經在使用on
或click
事件:
$(document).on('click', '#reply', function() {
alert('Reply here');
});
// or this ...
$('#reply').click(function() {
alert('Reply here');
});
但這仍然行不通。
請幫忙,謝謝^^
您需要更改兩件事:
$('#data-message').append("<button class='btn btn-default btn-xs reply' style='margin-top:5px;'>Reply</button>");
//-----------------change here-----------------------------------^^^^^
因為您處於循環狀態,並且您正在復制相同的ID。
將事件綁定更改為class:
$(document).on('click', '.reply', function() {
alert('Reply here');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.