javascript - body标签中的onbeforeunload和beforeunload有什么区别?
问题描述
有什么区别
<body onbeforeunload="return myFunction()">
和
$(window).on('beforeunload', function () {
myFunction();
});
解决方案
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 = '';
});
推荐阅读
- python - 寻找最佳模型并将其信息放入新列
- c# - 如何检测电报 TLSharp 上已编辑或已删除的消息
- ruby-on-rails - 构建带有docker的rails容器没有被复制公共文件夹下的所有文件
- ios - Taptic Engine 平滑反馈
- ffmpeg - FFMPEG DASH - 实时流式传输 MP3 剪辑序列
- xquery - XQuery 根据不同的值获取数据
- javascript - Javascript:打印 JSON 树中的所有路径,包括数组
- java - 嵌套for循环后卡住java空间
- python - 如何访问 Python 字符串中的第一个字符和整数对?
- python - 如何将html表单/文件名的名称传递给python - CGI/HTML/Python