Question

I have a checkout form that uses php to load some javascript & html into #Div-A when the page loads. The javascript binds a click event to #Button-A in the same div. Something like this:

<div id="#Div-A"><input type="button" id="Button-A"/>
<script type="text/javascript">
    $('#Button-A').bind('click', function() {
    $.ajax({ 
        type: 'get',
        url: 'some/url/gets/called',
        success: function() { this happens on success }     
    });
});</script>
</div>

Afterward, #Global-Button is created and a javascript function binds a different click event to this second button which then triggers #Button-A to be clicked like this:

$('#Global-Button').live('click', function(event) {
    $("#Button-A").trigger("click");
})

The reason being that the contents of #Div-A can change (via ajax), so the second button acts as a global trigger regardless of which button or function happens to reside in #Div-A.

The problem I'm encountering is that for some reason if #Global-Button is clicked after page load #Button-A gets triggered twice. If an Ajax event reloads the contents of #Div-A then all is well and the the trigger happens only once as it should.

I've examined the html within #Div-A before and after reloading via Ajax and everything appears to be identical. There are definitely no duplicate buttons or functions anywhere as far as I can see that would cause two events to be triggered.

I know only a very little about the DOM and can only guess this has something to do with the order in which things are loaded and events are bound.

Était-ce utile?

La solution

This is always recommended to use 'unbind' before bind to make sure the event is not bound multiple times. In your case, there may be two possibilities -

  1. '#Global-Button' click function is bound twice.
  2. '#Button-A' click function is bound twice and '#Global-Button' is actually triggering the click once.

Change your code like -

$('#Global-Button').unbind('click').bind('click', function(event) {
    $("#Button-A").trigger("click");
})

and also -

$('#Button-A').unbind('click').bind('click', function() {
    $.ajax({ 
        type: 'get',
        url: 'some/url/gets/called',
        success: function() { this happens on success }     
    });
});

Autres conseils

Don't use .live. Live is deprecated use .on instead

Every time you click on #Blobal-Button you are biding an click event.So you need to off before use it

Use .off to remove event handler

$('#Global-Button').off('click');
$('#Global-Button').on('click', function(event) {
    $("#Button-A").trigger("click");
})

You can also use

 $(".selector").on("click", function (**e**) {
  **e**.stopImmediatePropagation();//use to stop click twice or more
})
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top