我有一个ASP MVC应用程序,我有一个局部视图,每次添加新注释时都会通过ajax加载。
但是,在加载ajax页面后,jquery点击处理程序不再有效。
<div id="comments">
// Jquery links don't work after ajax page load?
<ul>
<li>
<div></div>
<a href="#" class="js-delete-comment" data-comment-id="@Model.comment.Id">
<i class="fa fa-trash-o" aria-hidden="true"></i> Delete
</a>
</li>
</div>
@using (Ajax.BeginForm("Create", "Comments", null, new AjaxOptions
{
HttpMethod = "POST",
LoadingElementId = "create-post-wait",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "comments",
OnComplete = "AjaxCreatePostComplete()"
}, new { enctype = "multipart/form-data" }))
{
@* form details *@
}
我的Jquery
$(function () {
DeleteComment();
}
var DeleteComment = function () {
if ($(".js-delete-comment").length === 0) {
return;
}
$(".js-delete-comment").click(function (e) {
var a = $(this); // "this" is the <a>
window.swal({
title: "Confirm",
text: "Are you sure you want to delete this comment?",
type: "warning",
showCancelButton: true
},
function () {
$.ajax({
// do stuff
})
});
});
};
var AjaxCreatePostComplete = function () {
var createButton = $("#create-post-btn");
if (createButton.length > 0) {
createButton.attr("disabled", false);
}
};
答案 0 :(得分:3)
使用jQuery on()。on()
和click()
之间的区别在于on()
适用于动态添加的元素。请尝试更改您的点击事件:
$(document).on('click','.js-delete-comment',function() {
//Add the logic for the click event here
});