How do I “rebind” the click event after unbind(

2019-01-14 08:36发布

问题:

I have an anchor tag <a class="next">next</a> made into a "button". Sometimes, this tag needs to be hidden if there is nothing new to show. All works fine if I simply hide the button with .hide() and re-display it with .show(). But I wanted to uses .fadeIn() and .fadeOut() instead.

The problem I'm having is that if the user clicks on the button during the fadeOut animation, it can cause problems with the logic I have running the show. The solution I found was to unbind the click event from the button after the original click function begins, and then re-bind it after the animation is complete.

$('a.next').click(function() {
    $(this).unbind('click');
    ...
    // calls some functions, one of which fades out the a.next if needed
    ...
   $(this).bind('click');
}

the last part of the above example does not work. The click event is not actually re-bound to the anchor. does anyone know the correct way to accomplish this?

I'm a self-taught jquery guy, so some of the higher level things like unbind() and bind() are over my head, and the jquery documentation isn't really simple enough for me to understand.

回答1:

I would just add a check to see if it's animating first:

$('a.next').click(function() {
    if (!$(this).is(":animated")) {
        // do stuff
    }
});


回答2:

When you rebind the click event, you're starting all over. You need to provide the function that you intend to handle the events. jQuery doesn't remember them for you after you call "unbind."

In this particular case, it's a little more complicated. The problem is that when you start up those animations you're setting into motion a series of actions that are driven by a timer. Thus, unbinding and rebinding the "click" handler inside the click handler itself really won't help anything. What would help (assuming you don't want to solve the problem with the is(":animated") trick) would be to unbind the handler and then rebind in the "finish" callback from your animation.

When you set up the "click" handler in the first place, you can separate the declaration of the function from the call to "click()":

var handler = function() {
  $(this).whatever();
};
$('a.next').click(handler);

Then, should you end up wanting to unbind/rebind, you can repeat that call to "click" and refer to the "handler" function the same way.



回答3:

A simpler and short solution

(without using the bind/unbind method)

is to add a class to the object if you want to unbind it then remove this class to rebind ex;

$('#button').click( function(){
   if($(this).hasClass('unbinded')) return;
   //Do somthing
 });

$('#toggle').click(function(){
    $('#button').toggleClass('unbinded');
 });