简体   繁体   English

JavaScript:窗口事件侦听器不起作用

[英]JavaScript: Window EventListener not working

I add the following event listener to the window object:我将以下事件侦听器添加到window对象:

window.addEventListener( 'popstate beforeunload', () => {
    console.log('test');
});

I'd expect that a console log entry is being created whenever I navigate the browsers history or reload the page.我希望每当我浏览浏览器历史记录或重新加载页面时都会创建一个控制台日志条目。 However, nothing happens.然而,什么也没有发生。 What am I doing wrong?我做错了什么?

If you want two event listeners, you need to add them separately.如果需要两个事件监听器,则需要分别添加。

var handler = () => {
  console.log('test');
};
window.addEventListener('popstate', handler);
window.addEventListener('beforeunload', handler);

Some libraries like jQuery's .on will automatically split on whitespace to allow this kind of thing, but .addEventListener itself does not.一些库,如 jQuery 的.on会自动拆分空白以允许这种事情,但.addEventListener本身不会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM