how to unbind and bind again

前端 未结 5 1123
野性不改
野性不改 2021-01-23 00:59
$(\"#archive\").click(function(event){
        /*do something*/
});

$(\'#archive2\').unbind(\'click\',event);

i have this click function that I unbind

相关标签:
5条回答
  • 2021-01-23 01:16

    You need to provide a handler to the function so you can bind/unbind from it. (Also allows you to bind/unbind specific events handlers within the same event:

    var handler = function() {
      alert('The quick brown fox jumps over the lazy dog.');
    };
    $('#foo').bind('click', handler);
    $('#foo').unbind('click', handler);
    

    (used from http://api.jquery.com/unbind/ )

    0 讨论(0)
  • 2021-01-23 01:19

    Why not have a boolean value and an if statement in the event handler?

    0 讨论(0)
  • 2021-01-23 01:20

    You have to keep a reference to the function (instead of passing an anonymous function):

    function handler() {
        // do something
    }
    
    $("#archive").click(handler); // bind the first time
    $("#archive").unbind('click', handler); // unbind
    $("#archive").click(handler); // bind again
    

    Not sure what is event in your case, but if it is the event object passed to the event handler then it does not make sense to pass it to unbind and bind.

    0 讨论(0)
  • 2021-01-23 01:20

    Try this:

    var closeHandle = function () {
          alert('close');        
    };
    
    function addClick() {       
             $("#btnTest").unbind('click').click(closeHandle);          
    }
    
    0 讨论(0)
  • 2021-01-23 01:21

    As of jQuery 1.7 you should use on and off for all your event handler binding:

    var handler = function() {
      alert('The quick brown fox jumps over the lazy dog.');
    };
    $('#foo').on('click', handler);
    $('#foo').off('click', handler);
    
    0 讨论(0)
提交回复
热议问题