Prevent multiple click events firing JQuery

后端 未结 2 597
后悔当初
后悔当初 2020-12-05 18:23

Here\'s the scenario, my content is loaded asynchronously based on a class. So if I have a link with the class ajaxLink it fires as below:

$(\'a.ajaxLink\').         


        
相关标签:
2条回答
  • 2020-12-05 18:34

    stopPropagation would stop the event from bubbling to parent elements, not prevent other click handlers on the same element from firing. So your solution won't work.

    You could do it like this for example:

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

    If you'd have a lot of different types of links you should put the common code in a function and bind the handlers using the differentiating class. These handlers can then call the common code when appropriate.

    0 讨论(0)
  • 2020-12-05 18:41

    Have you tried: event.stopImmediatePropagation?

    I believe it is what you are looking for:

    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();
            }
        });
    
    0 讨论(0)
提交回复
热议问题