简体   繁体   中英

How to rebind the events in jquery

I have some events like click, dblclick that are attached on large number of elements. To unbind click and dblclick events with all the elements at once I used this in jquery :

 $(document).unbind("click").unbind("dblclick");

Now I have to rebind these events to all the elements again. For this I used :

 $(document).bind("click").bind("dblclick");

But this is not working. Events are not rebind. How can I do this?

$(document).bind("click").bind("dblclick");

I don't think this will bind anything, you need callbacks.

$(document).bind("click", onClick).bind("dblclick", onDbClick);

Also, in this case you might want to consider using namespaced events :

$(document).bind("click.myclick", onClick)

And then later unbind only this event, leaving the other click untouched.

$(document).unbind("click.myclick");

PS It's now considered better practice to use the new on , off methods for binding.

unbind:

$(document).off("click", myFunction);

bind:

$(document).on("click", myFunction);

function myFunction() {
    alert('you clicked the document');
}

jQuery on() and off() would be the way to go, and when rebinding, the function would have to be passed in again, you can't just rebind and expect it to know what function to call.

The best way is to name the callback functions, just as @adeneo suggested. But sometimes you don't know when the handlers are bound (f.ex in a plugin), or perhaps you added anonymous callbacks using something like:

$(document).click(function() {
    // anonymous
});

then you can restore all those callbacks using the $._data object. Here is a function for you:

function restoreHandlers(elem, type) {
  var orig = $._data(elem, 'events');
  if ( type in orig ) {
    return $.map(orig[type], function(o) {
      return o.handler;
    });
  } else return [];
}

Use it like this (before you unbind):

var handlers = restoreHandlers(document, 'click');

then unbind:

$(document).off('click');

then rebind:

$.each(handlers, function(i, fn) {
    $(document).on('click', fn);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM