javascript 如果未提交表单,则触发 onbeforeunload
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4172671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trigger onbeforeunload if form is not submitted
提问by pingu
I've got a form which is being submitted via PHP with 3 submit actions:
我有一个通过 PHP 提交的表单,其中包含 3 个提交操作:
- Save and Continue
- Save and Exit
- Exit without Saving
- 保存并继续
- 保存并退出
- 退出而不保存
I'd like to trigger an "OnBeforeUnload" alert to display if the user DOES NOT click on any of the form actions to advise them that they're leaving the page, and their changes may not be saved.
我想触发“OnBeforeUnload”警报以显示如果用户没有点击任何表单操作来通知他们他们正在离开页面,并且他们的更改可能不会被保存。
I've tried the following code but it seems as though the unbeforeunload is being triggered before my click event. Any suggestions on how best to achieve this?
我已经尝试了以下代码,但似乎在我的点击事件之前触发了 unbeforeunload。关于如何最好地实现这一目标的任何建议?
$buttonpressed = false;
$j(".Actions input").click(function(){
$buttonpressed = true;
});
if(!$buttonpressed){
window.onbeforeunload = function(){
return "Your changes may not be saved.";
}
}
回答by Nick Craver
You need to do the check insidethe handler, like this:
您需要在处理程序内部进行检查,如下所示:
window.onbeforeunload = function(){
if(!$buttonpressed){
return "Your changes may not be saved.";
}
}
Currently it's binding window.onbeforeunloadwhen your code is run because $buttonpressedis falsewhen it runs...it doesn't matter if it changes later since you already bound the handler. An alternative is to make it a bit simpler, like this:
当前,它window.onbeforeunload在您的代码运行时绑定,因为它$buttonpressed是false在运行时绑定的……因为您已经绑定了处理程序,所以以后更改它并不重要。另一种方法是让它更简单一点,像这样:
window.onbeforeunload = function(){
return "Your changes may not be saved.";
}
$j(".Actions input").click(function(){
window.onbeforeunload = null;
});
This just removes the handler on clickinstead. A more appropriate event to handle other submit cases would be to attach to the submitevent, like this:
这只是删除了处理程序click。处理其他提交情况的更合适的事件是附加到submit事件,如下所示:
$j(".myForm").submit(function(){
window.onbeforeunload = null;
});

