在页面卸载前调用事件 [英] Event calling before page unload

查看:111
本文介绍了在页面卸载前调用事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在卸载 html 页面之前弹出一个对话框,询问是否卸载页面。如果选择是,则卸载继续,如果选择否,则取消卸载事件。

I want to pop up a dialog before an html page is unloaded asking to unload page or not. If yes is selected then the unload continues, and if no is selected then the unload event is canceled.

推荐答案

将文本设置为yes/no(在大多数浏览器中它会为Ok/Cancel),但是当以任何方式使用 window.onbeforeunload ,如下所示:

You can't set the text to "yes"/"no" (it'll be "Ok"/"Cancel" in most browsers), but you can prompt (be careful when using this) when leaving the page in any manner using window.onbeforeunload, like this:

window.onbeforeunload = function() {
  return "Are you sure you wish to leave the page?";
}

只有在有充分理由的情况下才能使用它,不要惹恼用户。这就是说,这会在离开页面时提示,包括历史记录,转发,刷新,关闭窗口/标签,点击链接以导航或提交表单等。所以你可能想要在去某个不应该提示的地方:

Only use this if you have a good reason, don't annoy your users. That being said, this will prompt when leaving the page, that includes history back, forward, refresh, closing the window/tab, clicking a link to navigate away or submitting a form, etc. So you'll probably want to call this when going somewhere that shouldn't prompt:

window.onbeforeunload = null;

例如,提交一种形式的信息,您希望在离开/丢失数据时提示,但实际上没有提交。

For example, submitting a form of information, you'd want to prompt when leaving/losing the data, but not when actually submitting it.

这篇关于在页面卸载前调用事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆