jQuery onlick事件在AjAX成功调用中不起作用



我正在开发一篇简单的博客文章,用户可以在其中发表评论和点赞。我在动态内容方面遇到了一些问题。当用户对帖子发表评论时,我会动态添加内容。

<script>
$(document).ready(function () {

$('#post-comment-{{my_post['_id'] | string}}').on('click', function () {
var post_id = $(this).attr('post_id');
var comment_content = $('#comment-textarea-' + post_id).val();
req = $.ajax({
url: '/post_comments',
type: 'POST',
data: { post_id: post_id, comment_content: comment_content }
});
req.done(function (response) {
var content = '<div class="mb-3">' +
'<div class="row align-items-top">' +
'<div class="col-auto ml-5"><img src="' + response.profile_pic + '" class="rounded-circle" /></div>' +
'<div class="col ml-n2">' +
'<a href = "/user_profile/' + response.user_id + '"><h1>' + response.first_name + ' ' + response.last_name + '</h1></a>' +
'<p class="small text-muted"><span class="far fa-clock mr-1"></span>' + str + '</p>' +
'<p>' + response.comment_content + '</p>' +
'</div>' +
'<div class="col-auto">' +
'<div class="dropdown">' +
**'<a href="#!" id="delete-comment-'+response.post_id+'-'+response.comment_id+'" role="button">' +
'<i class="fa fa-times" aria-hidden="true"></i>' +
'</a>' +**
'</div>' +
'</div>' +
'</div>' +
'</div>'
$('#view-post-comments-{{my_post['_id'] | string}}').append(linkify(nl2br(content)));
$('#comments-{{my_post['_id'] | string}}').html('<i class="far fa-comments mr-1 "></i>' +
'Comments (' + response.comment_count + ')');
});
});
});
</script>

这是我的删除ajax代码:

<script type="text/javascript">
$(document).ready(function () {
$(document).on('click','#delete-comment-{{my_post['_id'] | string}}-{{post_comments._id | string}}', function () {
$('#delete-comment-modal-{{my_post['_id'] | string}}-{{post_comments._id | string}}').modal('show');
});
$('#confirm-comment-delete-button-{{my_post['_id'] | string}}-{{post_comments._id | string}}').on('click', function () {
var post_id = $(this).attr('post_id');
var comment_id = $(this).attr('comment_id');
req = $.ajax({
url: '/delete_comments',
type: 'POST',
data: { post_id: post_id, comment_id: comment_id }
});
req.done(function (response) {
$('#delete-comment-modal-{{my_post['_id'] | string}}-{{post_comments._id | string}}').modal('hide');
$('#comments-{{my_post['_id'] | string}}').html('<i class="far fa-comments mr-1 "></i>' +
'Comments (' + response.comment_count + ')');
$('#show-each-comment-{{my_post['_id'] | string}}-{{post_comments._id | string}}').remove();
});
});
});
</script>

现在,如果代码在DOM中并且是静态的,那么它就可以正常工作了。对于我在第一次ajax成功调用中生成的动态内容,它不起作用。我需要刷新页面才能将其删除。如有任何帮助,我们将不胜感激。

我在ajax中创建了dunamic模态和链接,并调用了它的emf。

最新更新