[英]window.addEventListener('message', myFunction(event)) doesn't work
I'm trying to understand why the following does not work. 我试图了解以下原因为何不起作用。
var myFunction = function(event) {
// do something with event
};
window.addEventListener('message', myFunction(event));
I get the following error: "ReferenceError: event is not defined". 我收到以下错误:“ ReferenceError:未定义事件”。
However, the following works and event
is able to be used. 但是,可以使用以下作品和
event
。
window.addEventListener('message', function(event) {
// do something with event
});
How can I use event
in the first situation? 在第一种情况下如何使用
event
? Why is event
only accessible in the second situation? 为什么仅在第二种情况
event
才可以访问event
?
You are seeing the error because you are invoking the function immediately. 您看到此错误是因为您正在立即调用该函数。 You need to pass a reference to the function instead.
您需要传递对该函数的引用 。
In other words, change this: 换句话说,更改此:
window.addEventListener('message', myFunction(event));
to this: 对此:
window.addEventListener('message', myFunction);
When using the addEventListener()
method, the event
object will be passed as the first parameter by default when the event is fired. 使用
addEventListener()
方法时,在触发事件时默认情况下将event
对象作为第一个参数传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.