简体   繁体   中英

JavaScript: Window EventListener not working

I add the following event listener to the window object:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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