[英]return in an event function results in alert pop-up
I am following a book on JavaScript. 我正在关注一本关于JavaScript的书。 The page that puzzles me is the following: http://javascriptbook.com/code/c06/html5-events.html . 令我困惑的页面如下: http : //javascriptbook.com/code/c06/html5-events.html 。
When the user pressed "Next" button an event fires. 当用户按下“下一步”按钮时,事件将触发。 This is the code that specifies event listener: 这是指定事件侦听器的代码:
window.addEventListener('beforeunload', function(event) {
var message = 'You have changes that have not been saved';
(event || window.event).returnValue = message;
return message;
})
This code results in an alert and offers me to Stay on this page or Leave . 此代码会生成警报并提示我留在此页面或离开 。 I don't get the syntax here. 我在这里没有得到语法。 I thought that alerts are made with alert()
function. 我认为使用alert()
函数进行alert()
。 What is going or here? 到底发生了什么? Thanks for your help 谢谢你的帮助
This code returns a message, so browser takes care of confirming the user for navigation( or close) event, also that is why you get browser specific alert. 此代码返回一条消息,因此浏览器负责确认用户的导航(或关闭)事件,这也是您获得特定于浏览器的警报的原因。
window.addEventListener('beforeunload', function(event) {
var message = 'You have changes that have not been saved';
(event || window.event).returnValue = message;
return message; // alerts with this message.
});
If you try below code, which doesnt returns the message, then you won't get confirmation alert box, but you can still capture the event And do stuff. 如果您尝试下面的代码,它不会返回消息,那么您将无法获得确认警告框,但您仍然可以捕获事件并执行操作。
window.addEventListener('beforeunload', function(event) {
//var message = 'You have changes that have not been saved';
//(event || window.event).returnValue = message;
localStorage.eventCaptured = 'eventCaptured without alert'; // gets saved to localStorage
//return message;
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.