如何在适当的时候显示onbeforeunload对话框? [英] How to display onbeforeunload dialog when appropriate?
本文介绍了如何在适当的时候显示onbeforeunload对话框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的网页上有一个javascript编辑器,我想询问用户他/她是否想要离开页面,即使有未保存的更改。
I've got an editor in javascript on my webpage and I would like to ask user if he/she wants to leave the page even if there are unsaved changes.
我知道我可以通过这种方式向onbeforeunload对话框添加自定义消息:
I know I can add custom message to the "onbeforeunload dialog" this way:
window.onbeforeunload = function() {
return 'You have unsaved changes!';
}
( Source )但是我想只显示一些未保存的更改的对话框。怎么做?
(Source) but I want to display the dialog only where there really are some unsaved changes. How to do that?
谢谢!
推荐答案
你可以做类似这样的事情:
You can do something like this:
var unsavedChanges = false;
window.onbeforeunload = function() {
if (unsavedChanges) return 'You have unsaved changes!';
}
function makeSomeChange() {
// do some changes....
unsavedChanges = true;
}
您可以确保更改 unsavedChanges
在'change'事件处理程序中。
You can make sure to change unsavedChanges
in the 'change' event handlers.
这篇关于如何在适当的时候显示onbeforeunload对话框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文