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

时间:2012-10-03 12:40:31

标签: jquery confirm

这是场景,我的内容是根据类异步加载的。因此,如果我有一个类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是:

<a style="" href="/CMS/CreateANewHotel?regionID=3&amp;destinationID=1&amp;countryName=Australia" class="button wideBorderlessButton ajaxLink addANewHotel">Add a new hotel</a>

2 个答案:

答案 0 :(得分:36)

您是否尝试过: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();
        }
    });

答案 1 :(得分:2)

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');
            }
        });
    });

});

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