在使用ajax发布回复并使用ajax响应中的数据替换comments-section div后,回复按钮似乎不再触发jQuery函数
继承我的HTML
<div class="comments-section">
<?php
foreach ($comments as $c)
{?>
<div style="margin-bottom:5px" class="comment" data-commentID="<?php echo $c->id;?>">
<div style="border-radius:5px 5px 0px 0px;border:2px solid black;border-bottom-width:0px;padding:3px;font-weight:bold;">
<?php echo $c->user->username?>
</div>
<div style="border-radius:0px 0px 5px 5px;background-color:white;padding:5px;border:2px solid black">
<?php echo $c->comment;?>
<button class="reply-button">Reply</button>
</div>
</div>
<?php
}?>
</div>
继承我的jQuery功能
<script>
$(document).ready(function(){
$(".reply-button").on('click',function(){
var btn = $(this);
var reply_text = btn.siblings('.reply-text');
if(reply_text.length) {
$.ajax({
url: '/project/index.php/comments/postReply',
data: {
topic_id: '<?php echo $model->id ?>',
comment_id: $(this).closest('.comment').attr("data-commentID"),
comment: reply_text.val()
},
success: function(data) {
$data = $(data);
$('.comments-section').replaceWith($data.find('.comments-section'));
},
});
} else {
btn.before('<br><textarea style="resize:none" cols="84" rows="5" class="reply-text" placeholder="comment..."></textarea><br>');
}
});
});
</script>
答案 0 :(得分:0)
尝试使用委托事件,因为它们可以处理来自稍后添加到文档的后代元素的事件。
$(document).on( "click", ".reply-button", function() {
// place your click event code here
});