关闭具体点击事件 [英] Turning Off Specific Click Event

查看:143
本文介绍了关闭具体点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JSFIDDLE: http://jsfiddle.net/w55usyqk/

JSFIDDLE: http://jsfiddle.net/w55usyqk/

当您单击div时,会触发两个单独的点击事件。他们分别在控制台日志中打印出点击和点击。

When you click the div there are two separate click events fired. They print out "click" and "clicked" respectively in the console log.

$("div").on("click", function() { console.log("click"); });
$("div").on("click", function() { console.log("clicked"); });

如果您点击按钮,它将从div对象中删除这两个事件声明

If you tap on the button it will remove both event declarations from the div object

$("button").on("click", function() { $("div").off("click"); });

但是,如果我只需要删除一个点击事件怎么办?这是存储在某种事件数组中,我可以沿着 $(div)的行执行某些操作。off(click)[1] ;或者是否可以关闭一个而不关闭另一个?

However, what if I just needed to remove a single click event? Is this stored in some sort of event array where I could do something along the lines of $("div").off("click")[1]; or is it impossible to turn off one without turning off the other as well?

如果以前发布过,我确实尝试寻找答案。我认为这是很难说的问题之一,所以尽管可能有一个答案,但很难确定。

I did try looking for the answer if it's been posted before. I think this is one of those questions that's hard to word, so though there may be an answer out there, it's difficult to pin down.

推荐答案

您可以使用命名空间轻松实现。创建事件处理程序后,在事件之后添加命名空间。例如:

You can use namespaces to easily do this. When you create your event handlers, add the namespace after the event. Ex:

$("div").on("click.namespace1", function() { console.log("click"); });
$("div").on("click.namespace2", function() { console.log("clicked"); });

然后为您的按钮,使用事件的命名空间删除:

then for your button, use the namespace of the event to remove:

// remove only the event for namespace2
$("button").on("click", function() { $("div").off(".namespace2"); });

jsFiddle示例

jsFiddle example

更多关于事件的命名空间


事件名称可以通过简化$的事件命名空间进行限定b $ b删除或触发事件。例如,click.myPlugin.simple
为这个特定的
点击事件定义了myPlugin和简单命名空间。通过该字符串附加的点击事件处理程序可能是
被删除与 .off(click.myPlugin) .off .simple)没有
打扰附加到元素的其他点击处理程序。命名空间
类似于CSS类,因为它们不是层次结构;只有一个
名称需要匹配。以下划线开头的命名空间是
,用于jQuery的使用。

An event name can be qualified by event namespaces that simplify removing or triggering the event. For example, "click.myPlugin.simple" defines both the myPlugin and simple namespaces for this particular click event. A click event handler attached via that string could be removed with .off("click.myPlugin") or .off("click.simple") without disturbing other click handlers attached to the elements. Namespaces are similar to CSS classes in that they are not hierarchical; only one name needs to match. Namespaces beginning with an underscore are reserved for jQuery's use.

这篇关于关闭具体点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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