我在最右边的列中有一个包含可点击行和ajax链接的表。 当我点击行中的链接时,行点击事件也会被触发。
为了停止事件传播,我使用了stopPropagation来停止行点击事件触发。然而,ajax get成为普通的HTML get,导致加载新页面。
如何让AJAX与停止传播一起工作?
感谢。
以下是我的代码:
<tr data-id="@user.UserId" style="cursor:pointer">
<td>
@Html.DisplayFor(modelItem => user.UserName)
</td>
<td>
@Html.DisplayFor(modelItem => user.Name)
</td>
<td>
@Html.DisplayFor(modelItem => user.LastLogin)
</td>
<td>
@Ajax.ActionLink("Delete", "Delete", new { id = user.UserId }, new AjaxOptions
{
HttpMethod = "GET",
OnSuccess = "getModalSuccess"
}) |
@Ajax.ActionLink("Reset password", "ResetPassword", new { id = user.UserId }, new AjaxOptions
{
HttpMethod = "GET",
OnSuccess = "getModalSuccess"
})
</td>
</tr>
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.js")
<script>
$(function () {
$('#user-list > tbody > tr').click(function () {
var url = "/Account/Edit/" + $(this).data('id');
$.get(url, getModalSuccess);
});
// To stop propagation to parent, which causes event above fired
$('#user-list > tbody > tr > td > a').click(function (e) {
e.stopPropagation();
});
});
function getModalSuccess(data) {
$('#modal-container').html(data);
$('#modal-dialog').modal('show');
$('form').removeData('validator');
$('form').removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('form');
$('form').validate();
}
</script>
生成的HTML
<a data-ajax="true" data-ajax-method="GET" data-ajax-success="getModalSuccess" href="/Account/Delete/b9b70187-1188-4398-96f7-cda32e67b14a">Delete</a>
答案 0 :(得分:0)
问题是,上次我检查时,不显眼的Ajax使用以下构造来加载绑定。
$("a[data-ajax=true]").live("click", function (evt) {
evt.preventDefault();
asyncRequest(this, {
url: this.href,
type: "GET",
data: []
});
});
此构造绑定到document
事件。换句话说,事件会冒泡到文档,然后才会发生ajax。通过调用e.stopPropagation();
,您可以明确地停止将事件冒泡到附加了ajax制作处理程序的文档,因此它不会被执行。
答案 1 :(得分:0)
为自己找到了解决方案。 我没有将实际链接放在锚点的href中,而是使用jquery .get()和stopPropagation()来处理click事件。下面的代码
<a href="#" data-url='/Account/Delete/@user.UserId'>Test</a>
$('#user-list > tbody > tr > td > a').click(function (e) {
var url = $(this).data('url');
$.get(url, getModalSuccess);
e.stopPropagation();
});