防止触发JQuery的多次单击事件

这是场景,我的内容是基于类异步加载的。 因此,如果我有一个类ajaxLink的链接,它会触发如下:

$('a.ajaxLink').click(function (e) { e.preventDefault(); var container = $(this).parents('div.fullBottomContent'); var href = $(this).attr('href'); container.fadeOut('fast', function () { $.ajax({ url: href, dataType: "html", type: "GET", success: function (data) { container.html(data); BindEventHandlers(); container.fadeIn(); $.validator.unobtrusive.parse('form'); }, error: function () { alert('An error has occurred'); } }); }); }); 

都很可爱。 现在在一个实例中,我想向用户显示一个警告,以confirm他们想要加载页面并松开所有更改,所以我写了这个:

 $('a.addANewHotel').click(function (e) { if (!confirm('Adding a new hotel will loose any unsaved changes, continue?')) { e.stopPropagation(); } }); 

现在我试过return falsee.preventDefault()e.stopPropagation(); 但无论第一种方法总是被解雇? 如何防止额外的点击事件被触发? 这是事件的顺序吗?

不知道这是如何相关的,但我的HTML是:

 Add a new hotel 

你试过了吗: event.stopImmediatePropagation

我相信这正是你要找的:

http://api.jquery.com/event.stopImmediatePropagation/

 $('a.addANewHotel').click(function (e) { if (!confirm('Adding a new hotel will loose any unsaved changes, continue?')) { e.stopImmediatePropagation(); e.preventDefault(); } }); 

stopPropagation会阻止事件冒泡到父元素,而不会阻止同一元素上的其他点击处理程序触发。 所以你的解决方案不起作用。

你可以这样做,例如:

 $('a.ajaxLink').click(function (e) { e.preventDefault(); if($(this).hasClass("a.addANewHotel") && !confirm('Adding a new hotel will loose any unsaved changes, continue?')){ return false; } var container = $(this).parents('div.fullBottomContent'); var href = $(this).attr('href'); container.fadeOut('fast', function () { $.ajax({ url: href, dataType: "html", type: "GET", success: function (data) { container.html(data); BindEventHandlers(); container.fadeIn(); $.validator.unobtrusive.parse('form'); }, error: function () { alert('An error has occurred'); } }); }); }); 

如果你有很多不同类型的链接,你应该将公共代码放在一个函数中,并使用区分类绑定处理程序。 然后,这些处理程序可以在适当时调用公共代码。