简体   繁体   English

window.addEventListener('message',myFunction(event))不起作用

[英]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.

相关问题 window.addEventListener("message", getData); 在 safari 中不起作用? - window.addEventListener("message", getData); doesn't work in safari? 反应 window.addeventlistener 不起作用 - React window.addeventlistener doesn't work 使用 window.addEventListener 隐藏 div 不起作用 - Hide div with window.addEventListener doesn't work 使用 window.addEventListener('/load', myFunction); 在第二个 html 页面上? - use window.addEventListener('/load', myFunction); on the second html page? 为什么 window.addEventListener('scroll', this.someScrollHandler, false) 在 IE 10 上不起作用? - Why doesn't window.addEventListener('scroll', this.someScrollHandler, false) work on IE 10? window.addEventListener(“mousedown”, function()) 在 IE11 上不起作用 - window.addEventListener(“mousedown”, function()) doesn't work on IE11 window.addEventListener 未按预期更新 state - window.addEventListener doesn't update state as expected window.addEventListener 不会抛出错误或 go 进入 function - window.addEventListener doesn't throw an error or go into the function JavaScript window.addEventListener('blur')无法正常工作 - Javascript, window.addEventListener('blur') won't work 从iframe发出的消息上的window.addEventListener - window.addEventListener on a message emitted from an iframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM