how to unbind and bind again

2020-04-16 19:23发布

$("#archive").click(function(event){
        /*do something*/
});

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

i have this click function that I unbind. however, i want to bind it again when i click a certain button.

$("#archive").bind("click",event);

im using this code to bind again, however it doesn't seem to work. any suggestions or workarounds?

5条回答
唯我独甜
2楼-- · 2020-04-16 19:55

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);
查看更多
再贱就再见
3楼-- · 2020-04-16 19:57

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

查看更多
够拽才男人
4楼-- · 2020-04-16 20:07

Try this:

var closeHandle = function () {
      alert('close');        
};

function addClick() {       
         $("#btnTest").unbind('click').click(closeHandle);          
}
查看更多
神经病院院长
5楼-- · 2020-04-16 20:19

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.

查看更多
可以哭但决不认输i
6楼-- · 2020-04-16 20:21

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/ )

查看更多
登录 后发表回答