删除特定对象上的jQuery委托事件处理程序 [英] Remove jQuery delegated event handler on specific object

查看:130
本文介绍了删除特定对象上的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的关闭文档说我需要提供一个字符串作为第二个参数,而不是一个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");
});

演示@ 小提琴

示例HTML:

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

这篇关于删除特定对象上的jQuery委托事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆