简体   繁体   English

使用off()删除Jquery中元素的其他处理程序

[英]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. 我有以下小提琴 ,其中有两个事件处理程序附加到按钮的click事件。 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. 我的目标是使第二个事件处理程序删除第一个事件处理程序,以便在用户按下按钮时仅向用户显示Hello2 I have read here that off() method is designed to implement this, but I fail to reach the goal. 我在这里读到off()方法旨在实现此目的,但我未能达到目标。 My guess is that I am using $(document).on(... syntax. Any ideas? I have spent half day on this!! 我的猜测是我正在使用$(document).on(...语法。有什么想法吗?

UPDATE: 更新:

Put in other words, I want the second event listener to cancel out/deactivate the first one. 换句话说,我希望第二个事件侦听器取消/停用第一个事件侦听器。

From W3Schools: 从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');
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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