开发者

Jquery remove and add back click event

开发者 https://www.devze.com 2023-02-08 09:46 出处:网络
Is it possible to remove than add back click event to specific element? i.e I have a $(\"#elem\").click(function{//some behaviour});, $(\".elem\").click(function{//some behaviour});(there are开发者_

Is it possible to remove than add back click event to specific element? i.e

I have a $("#elem").click(function{//some behaviour});, $(".elem").click(function{//some behaviour});(there are开发者_运维百科 more than 1 element) while my other function getJson is executing I'd like to remove the click event from the #elem, and add it again onsuccess from getJson function, but preserve both mouseenter and mouseleave events the whole time?

Or maybe create overlay to prevent clicking like in modal windows? is that better idea?

edit :

I've seen some really good answers, but there is one detail that I omitted not on purpose. There are more than one element, and I call the click function on the className not on elementId as I stated in the original question


Rather than using unbind(), which means you'll have to rebind the same event handler later, you can use jQuery's data() facility with the ajaxStart and ajaxStop events to have your elements ignore click events during all AJAX requests:

$(".elem").click(function() {
    if (!$(this).data("ajaxRequestPending")) {
        // some behaviour
    }
}).ajaxStart(function() {
    $(this).data("ajaxRequestPending", true);
}).ajaxStop(function() {
    $(this).removeData("ajaxRequestPending");
});

EDIT: This answer is also id-to-class-proof (see questioner's edit), since everything matching the selector will handle the AJAX events the right way. That's the main selling point of jQuery, and it shows.


You are looking for .unbind(). Pass it 'click' and it will destroy the click event.

I would put it just before your getJSON and re-bind the click event inside the success handler of your ajax call.


You have to do some additional scripting. There is no callback for that. Take a look over here: jQuery - How can I temporarily disable the onclick event listener after the event has been fired?


Rather than unbinding/binding the click event, you could check the state of another variable to see if it should do the action.

var MyObject = {
  requestActive = false;
};

function MyJsonFunction() {
  // when requesting
  MyObject.requestActive = true;
  //...
  // when request over
  MyObject.requestActive = false;

}

$("#elem").click(function{
  if (MyObject.requestActive == true) {
    //do something
  }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消