问题描述
我得到一个 Uncaught TypeError:Illegal invocation
这个尝试放下EventListener的两个版本:(我应该在添加监听器时收到错误,而不是在我点击目标)
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)
ronan.addEventListener(click,alert,false);
addEventListener.apply(ronan,[click,alert,false]);
ronan
是一个 div
元素,由控制台成功返回,所以我没有认为这是问题所在。有什么想法我得到这个错误?我阅读了主题,我无法从中找到它。
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 this thread and I couldn't figure it out from that.
推荐答案
您需要在函数中包装 alert
。这将有效:
You need to wrap alert
in a function. This will work:
ronan.addEventListener("click", function() { alert('Hi'); }, false);
这是一个以证明。单独使用 alert
不起作用,因为当执行一个监听器时,该函数中的这个
的值被设置为它正在聆听的对象。例如,如果您在 ronan
上设置了一个侦听器,则在该侦听器中这个=== ronan
。这对 alert
提出了一个问题,因为该函数需要此
等于窗口
。你可以通过将函数包装在另一个函数中或通过将它绑定到它所期望的任何这个
来解决这个问题(没有双关语):
Here's a fiddle for 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:
document.body.addEventListener('click', alert.bind(window), false);
不要忘记在IE< 9你需要使用 attachEvent
而不是 addEventListener
。
Don't forget that in IE < 9 you need to use attachEvent
rather than addEventListener
.
关于使用的说明
/ 使用 code> addEventListener
A note on using apply
/call
with addEventListener
你的第二次尝试不起作用,因为你试图将你的论据应用于 window.addEventListener
,而不是 HTMLElement.prototype.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:
// 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]);
这篇关于未捕获的TypeError:addEventListener上的非法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!