首页 > 解决方案 > body标签中的onbeforeunload和beforeunload有什么区别?

问题描述

有什么区别

<body onbeforeunload="return myFunction()">

$(window).on('beforeunload', function () {
    myFunction();
});

标签: javascriptjquery

解决方案


onbeforeunload事件在文档即将被卸载时发生。

此事件允许您在确认对话框中显示一条消息,以通知用户他/她是要留下还是离开当前页面显示在下面的代码片段中。

确认框中显示的默认消息在不同的浏览器中有所不同。但是,标准消息类似于“您确定要离开此页面吗?”。此消息无法删除。

<!DOCTYPE html>
<html>
<body onbeforeunload="return myFunction()">

<p>Reload this page, or click on the link below to invoke the onbeforeunload event.</p>

<a href="https://stackoverflow.com/">Click here to go to stackoverflow.com</a>
    
<script>
function myFunction() {
  return "Write something clever here...";
}
</script>

</body>
</html>

当窗口、文档及其资源即将被卸载时,会触发beforeunload事件。文档仍然可见,此时事件仍然可以取消。

 window.addEventListener('beforeunload', (event) => {
  // Cancel the event as stated by the standard.
  event.preventDefault();
  // Chrome requires returnValue to be set.
  event.returnValue = '';
});

推荐阅读