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
Uncaught TypeError: Illegal invocation on addEventListener
提问by Artur Sapek
I get an Uncaught TypeError: Illegal invocation
for 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]);
ronan
is a div
element 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.
ronan
是div
控制台成功返回的元素,所以我认为这不是问题。任何想法为什么我会收到此错误?我读了这个线程,但我无法从中弄清楚。
回答by Matthew
You need to wrap alert
in a function. This will work:
您需要包装alert
在一个函数中。这将起作用:
ronan.addEventListener("click", function() { alert('Hi'); }, false);
Here's a fiddlefor proof. Using alert
alone doesn't work because when a listener is executed the value of this
within 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 alert
because that function expects this
to 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 this
to 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 attachEvent
rather than addEventListener
.
不要忘记在 IE < 9 中你需要使用attachEvent
而不是addEventListener
.
A note on using apply
/call
with 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]);