删除特定对象上的 jQuery 委托事件处理程序

我使用单个选择器将委托事件处理程序附加到页面上的许多元素.由于事件是针对单个元素触发的,我想仅关闭该元素的事件处理程序基于某些条件逻辑.这意味着我不一定要在第一次点击时禁用该事件.但是如果不关闭所有这些,我不知道该怎么做.

I've attached delegated event handlers to a number of elements on the page using a single selector. As the events are triggered for individual elements, I'd like to turn off only that element's event handler based on some conditional logic. That means I won't necessarily want to disable the event on the very first click. But I can't figure out how to do it without turning off all of them.

HTML:

<button>One</button>
<button>Two</button>
<button>Three</button>

JS:

$(document).on('click', 'button', function(ev) {
    // doesn't work because argument needs to be a string
    $(document).off('click', $(ev.target));

    // doesn't do what I want b/c turns off events on all buttons, not just this one
    $(document).off('click', 'button');

    // doesn't work because event is on document, not button
    $(ev.target).off('click');
});

jQuery 的 off 文档 说我需要提供一个 string 作为第二个参数,不是 jQuery 对象 ($(ev.target)),但如果我提供一个字符串,则没有值仅指单击的项目.

jQuery's off documentation says I need to provide a string as the second argument, not a jQuery object ($(ev.target)), but if I provide a string, there's no value that refers only to the item clicked.

来自 jQuery 的关闭文档:

From jQuery's off documentation:

要删除特定的委托事件处理程序,请提供一个选择器争论.选择器字符串必须与传递给的字符串完全匹配.on() 附加事件处理程序时.删除所有委派在不删除非委托事件的情况下从元素中获取事件,使用特殊值**".

To remove specific delegated event handlers, provide a selector argument. The selector string must exactly match the one passed to .on() when the event handler was attached. To remove all delegated events from an element without removing non-delegated events, use the special value "**".

那么如何关闭特定元素的委托事件处理程序?

So how do I turn off a delegated event handler for a specific element?

这是上面代码的JSFiddle

更新:根据提供的初步答案,添加了一些不起作用的选项示例.

UPDATE: Added a few examples of options that don't work, based on initial answers provided.

推荐答案

在网上看过之后,答案是你不能!您可以删除全部或不删除.解决方法可能类似于以下内容.

After having read thru on the web, the answer is you can't! You can either remove all or none. A workaround could be something like the following.

$(document).on('click', '.btn', function (ev) {
    alert('pressed');
    $(this).removeClass("btn");
});

Demo@小提琴

示例 HTML:

<button class="btn">One</button>
<button class="btn">Two</button>
<button class="btn">Three</button>

相关文章