javascript 如何删除事件处理程序 document.onkeydown?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17672850/
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-10-27 09:09:02  来源:igfitidea点击:

How to remove an eventhandler document.onkeydown?

javascriptjquery

提问by GibboK

I have this code, I would need programmatically overridde or remove onkeydown from document (for example using a simple condition)

我有这个代码,我需要以编程方式覆盖或从文档中删除 onkeydown(例如使用一个简单的条件)

document.onkeydown = function (f) {
    myMethod();
};

Any idea how to do it?

知道怎么做吗?

回答by Willem D'Haeseleer

document.onkeydown = null

You could use jquery to do your event handeling for you, the method you use is less commonly used and doesn't allow multiple subscribers.

您可以使用 jquery 为您处理事件,您使用的方法不太常用,并且不允许多个订阅者。

Look at the documentation here:

看看这里的文档:

http://api.jquery.com/on/

http://api.jquery.com/on/

example:

例子:

$(document).on("keydown", function(){
    doStuff();
})
// unsubscribe all handlers
$(document).off("keydown");

回答by Barmar

You can remove it with:

您可以使用以下方法删除它:

document.onkeydown = null;

If you want to be able to restore it, you can save it into a variable first:

如果你想能够恢复它,你可以先将它保存到一个变量中:

var saved_keydown = document.onkeydown;
document.onkeydown = null;
//... later
document.onkeydown = saved_keydown;

回答by ardhitama

The easiest way is set it to null

最简单的方法是将其设置为 null

document.onkeydown = null;

回答by adeneo

You can't remove it, you can only attach a new one that does nothing, like :

你不能删除它,你只能附加一个什么都不做的新的,比如:

document.onkeydown = function () {};

with jQuery you can do:

使用 jQuery,您可以执行以下操作:

$(document).on('keydown', myMethod);

and to remove

并删除

$(document).off('keydown', myMethod);