jquery 打开和关闭事件处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9918165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:27:48  来源:igfitidea点击:

jquery turning "on" and "off" event handlers

jqueryevents

提问by Chin

How would I apply the "off" directive to a named handler?

我如何将“off”指令应用于命名处理程序?

ex

前任

var $btn = $("#theBtn");
var namedHandler = $btn.on("click", function() {
//do something
//then turn off
})

would I turn it off like this

我会像这样关掉它吗

$btn.off("click");

or could I do something else now it is stored in a variable?

或者我现在可以做其他事情它存储在一个变量中吗?

namedHandler.off("click");

or

或者

namedHandler.off();

etc.

等等。

Any pointers much appreciated.

任何指针都非常感谢。

采纳答案by alex

The same reference to the jQuery object will be in $btnandnamedHandler. Both return a reference to the same thing so the assignment is assigning the same thing.

对 jQuery 对象的相同引用将在$btn和 中namedHandler。两者都返回对同一事物的引用,因此赋值是分配相同的事物。

You could turn it off()with either method.

你可以off()用任何一种方法来转动它。

What may be more suited to your example is namespacingyour event, so off('click', ...)won't unbind allclickevents.

可能更适合您的示例的是为您的 event命名空间,因此off('click', ...)不会取消绑定所有click事件。

回答by The Alpha

You can also do this

你也可以这样做

function handleClick(event) 
{
    // code
}

$('#btn').on('click', handleClick);

$('#btn').off('click', handleClick);

Some usefull examples only about on/off here.

一些有用的例子只在这里开/关。

回答by user

In addition to what @alex & @WereWolf said, I often find this useful :

除了@alex 和@WereWolf 所说的,我经常发现这很有用:

For a single use event handler, you can use .one()instead of .on()followed by .off()

对于一次性事件处理程序,您可以使用.one()而不是.on()后跟.off()

$( "#foo" ).one( "click", function() {
  alert( "This will be displayed only once." );
});

http://api.jquery.com/one/

http://api.jquery.com/one/

回答by Andreas Wong

You could define a function for your handler and pass it to .off()to disable that handler and .on()to reenable it.

您可以为处理程序定义一个函数并将其传递给以.off()禁用该处理程序并.on()重新启用它。

The documentation provides examples to achieve this

该文档提供了实现此目的的示例

http://api.jquery.com/off/

http://api.jquery.com/off/

function aClick() {
  $("div").show().fadeOut("slow");
}
$("#bind").click(function () {
  $("body").on("click", "#theone", aClick)
    .find("#theone").text("Can Click!");
});
$("#unbind").click(function () {
  $("body").off("click", "#theone", aClick)
    .find("#theone").text("Does nothing...");
});