javascript - 关闭特定的点击事件

标签 javascript jquery html events

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

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

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

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

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

但是,如果我只需要删除一个单击事件怎么办?这是否存储在某种事件数组中,我可以按照 $("div").off("click")[1]; 的方式做一些事情?还是不可能在不关闭另一个的情况下关闭一个?

如果以前发布过,我确实尝试寻找答案。我认为这是难以用语言表达的问题之一,因此尽管可能有答案,但很难确定。

最佳答案

您可以使用 namespace 轻松地做到这一点。创建事件处理程序时,在事件之后添加命名空间。例如:

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

然后对于您的按钮,使用事件的命名空间来删除​​:

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

jsFiddle example

关于 namespaces for events 的更多信息:

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.

关于javascript - 关闭特定的点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33045624/

相关文章:

javascript - 如何动态添加带有文本框的表格行?

javascript - Kendo optionLabel 下拉菜单无法正常工作

javascript - 当前用于将 html + svg + css 转换为 pdf 的库

javascript - 转换 tfjs 模型以在 C++ 中的 Tensorflow 中使用

javascript - 在 JavaScript 中检测 Flash 对象点击

javascript - ul li navigation - 从onclick获取参数值

php - 将 PHP 网站转换为基于 HTML 的网站

jQuery .hasClass、.closest() 和 $(this)

c# - 条件 anchor

javascript - 了解 $ 和 _(下划线)差异的 asp.net clientid 生成