Javascript 未捕获的类型错误:addEventListener 上的非法调用

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

Uncaught TypeError: Illegal invocation on addEventListener

javascriptaddeventlistener

提问by Artur Sapek

I get an Uncaught TypeError: Illegal invocationfor both versions of this attempt to put down an EventListener: (I get the error when the listener should be added, not when I click on the target)

Uncaught TypeError: Illegal invocation对于这种尝试放下 EventListener 的两个版本,我都得到了一个 :(应该添加侦听器时出现错误,而不是单击目标时)

ronan.addEventListener("click", alert, false);

ronan.addEventListener("click", alert, false);

addEventListener.apply(ronan, ["click", alert, false]);

addEventListener.apply(ronan, ["click", alert, false]);

ronanis a divelement that is returned successfully by the console so I don't think that's the problem. Any ideas why I get this error? I read thisthread and I couldn't figure it out from that.

ronandiv控制台成功返回的元素,所以我认为这不是问题。任何想法为什么我会收到此错误?我读了这个线程,但我无法从中弄清楚。

回答by Matthew

You need to wrap alertin a function. This will work:

您需要包装alert在一个函数中。这将起作用:

ronan.addEventListener("click", function() { alert('Hi'); }, false);

Here's a fiddlefor proof. Using alertalone doesn't work because when a listener is executed the value of thiswithin that function is set to the object on which it is listening. For example, if you set a listener on ronan, within that listener this === ronan. This presents a problem for alertbecause that function expects thisto be equal to window. You can work around this (no pun intended) by wrapping the function in another function or by binding it to whatever it expects thisto be:

这是证明的小提琴alert单独使用是行不通的,因为当执行侦听器时,this该函数内的值被设置为它正在侦听的对象。例如,如果您ronan在该侦听器内设置了一个侦听器this === ronan。这带来了一个问题,alert因为该函数期望this等于window。您可以通过将函数包装在另一个函数中或将其绑定到它期望的任何内容this来解决这个问题(没有双关语意):

document.body.addEventListener('click', alert.bind(window), false);

Don't forget that in IE < 9 you need to use attachEventrather than addEventListener.

不要忘记在 IE < 9 中你需要使用attachEvent而不是addEventListener.



A note on using apply/callwith addEventListener

使用上的注意事项apply/call使用addEventListener

Your second attempt won't work because you're trying to apply your arguments to window.addEventListener, as opposed to HTMLElement.prototype.addEventListener, which is a different function altogether:

您的第二次尝试将不起作用,因为您试图将参数应用于window.addEventListener,而不是HTMLElement.prototype.addEventListener,这是一个完全不同的函数:

// This won't work
addEventListener.apply(ronan, ["click", alert.bind(window), false]);

// This will work
HTMLElement.prototype.addEventListener.apply(ronan, ['click', alert.bind(window), false]);