jQuery click events firing multiple times

后端 未结 25 2231
不知归路
不知归路 2020-11-22 11:01

I\'m attempting to write a video poker game in Javascript as a way of getting the basics of it down, and I\'ve run into a problem where the jQuery click event handlers are f

相关标签:
25条回答
  • 2020-11-22 11:37

    .unbind() is deprecated and you should use the .off() method instead. Simply call .off() right before you call .on().

    This will remove all event handlers:

    $(element).off().on('click', function() {
        // function body
    });
    

    To only remove registered 'click' event handlers:

    $(element).off('click').on('click', function() {
        // function body
    });
    
    0 讨论(0)
  • 2020-11-22 11:39

    To make sure a click only actions once use this:

    $(".bet").unbind().click(function() {
        //Stuff
    });
    
    0 讨论(0)
  • 2020-11-22 11:39

    an Event will fire multiple time when it is registered multiple times (even if to the same handler).

    eg $("ctrl").on('click', somefunction) if this piece of code is executed every time the page is partially refreshed, the event is being registered each time too. Hence even if the ctrl is clicked only once it may execute "somefunction" multiple times - how many times it execute will depend on how many times it was registered.

    this is true for any event registered in javascript.

    solution:

    ensure to call "on" only once.

    and for some reason if you cannot control the architecture then do this:

    $("ctrl").off('click'); $("ctrl").on('click', somefunction);

    0 讨论(0)
  • 2020-11-22 11:40

    .one()

    A better option would be .one() :

    The handler is executed at most once per element per event type.

    $(".bet").one('click',function() {
        //Your function
    });
    

    In case of multiple classes and each class needs to be clicked once,

    $(".bet").on('click',function() {
        //Your function
        $(this).off('click');   //or $(this).unbind()
    });
    
    0 讨论(0)
  • 2020-11-22 11:41

    When I deal with this issue, I always use:

    $(".bet").unbind("click").bind("click", function (e) {
      // code goes here
    }
    

    This way I unbind and rebind in the same stroke.

    0 讨论(0)
  • 2020-11-22 11:42

    I was having this problem with a dynamically generated link:

    $(document).on('click', '#mylink', function({...do stuff...});

    I found replacing document with 'body' fixed the issue for me:

    $('body').on('click', '#mylink', function({...do stuff...});

    0 讨论(0)
提交回复
热议问题