How to prevent events from being bound multiple times

后端 未结 5 1360
后悔当初
后悔当初 2021-01-01 15:10
 $(\'.ajax\').click
 (        
    function()
    {
        // If been bound then we need to return here.
        alert(\':D\');
    }
 )

 $(\'.ajax\').click
 (
            


        
相关标签:
5条回答
  • 2021-01-01 15:41

    try unbinding it before binding:

    $(".ajax").unbind("click").click( 
          function () { 
        alert("Hello"); 
      } );
    

    read this for some more information.

    0 讨论(0)
  • 2021-01-01 15:47

    If using jQuery >= 1.7 you can use .on()/.off() API in conjunction with an event namespace. In this example .off() is called immediately to ensure previous events (of any kind) with the namespace are un-bound:

    $("form")
        .off(".validator")
        .on("keypress.validator", "input[type='text']", validate);
    

    It's quite a flexible API so you can be very specific if you need to be:

    $("form")
        .off("keypress.validator", "input[type='text']", validate)
        .on("keypress.validator", "input[type='text']", validate);
    

    The docs: http://api.jquery.com/off/

    0 讨论(0)
  • 2021-01-01 15:57

    There's a really good way to do this in jQuery.

    Here's an example.

    function alertEvent() {
       alert(":D");
    }
    $(".ajax").bind("click", alertEvent);
    //When you want to ensure it won't happen twice...
    $(".ajax").unbind("click", alertEvent);
    $(".ajax").bind("click", alertEvent);
    

    This method will only remove the event you specify, which makes it ideal for what you want to do.

    0 讨论(0)
  • 2021-01-01 15:58
    function demo()
    {
    // your code here which will called on click event
    }
    
    $(document).ready(function(){
    $('.add').bind('click',demo);
    
    });
    
    //After successfully ajax call response
    //Unbind the click event first
    $('.add').unbind('click',demo);
    //Then again bind the event
    $('.add').bind('click',demo);
    
    0 讨论(0)
  • 2021-01-01 15:59

    Simplest solution from here bind event only once

    Copied code sample:

    function someMethod()
    {
        $(obj).off('click').on('click', function(e) {
            // put your logic in here 
        });
    }
    
    0 讨论(0)
提交回复
热议问题