简体   繁体   中英

Removing other handlers of the element in Jquery using off()

I have the following Fiddle in which I have two event handlers attached to the click event of a button. And my goal is to make the second event handler remove the first one so that only Hello2 is displayed to the user as he presses the button. I have read here that off() method is designed to implement this, but I fail to reach the goal. My guess is that I am using $(document).on(... syntax. Any ideas? I have spent half day on this!!

UPDATE:

Put in other words, I want the second event listener to cancel out/deactivate the first one.

From W3Schools:

// Remove the click event for all <p> elements
$("button").click(function(){
  $("p").off("click");
});

Dont know if this is what you are looking for. But this is one way to do it:

$(function()
{
    $(document).on('click', 'button', function(e){
       alert('hello1');
       e.stopImmediatePropagation();
    });

    $(document).on('click', 'button', function(){
       alert('hello');
    });
});

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