![](/img/trans.png)
[英]How to handle 'Are you sure you want to navigate away from this page' on page close?
[英]How to prevent “Are you sure you want to navigate away from this page?” alert on form submission?
我有一个简单的html表单,其中包含很少的字段。
我想确保用户在尝试离开页面时收到警告消息。 所以我在页面上添加了脚本,只要用户试图离开此页面,该脚本就会运行。
但是当用户尝试提交表单时,我也收到此警报消息。 当用户保存表单时,我不想要此警报消息。
请帮忙。
下面是一些示例代码。
<html>
<head>
<script>
function verifyexit() { return 'Are you sure ?'; } window.onbeforeunload = verifyexit;
</script>
</head>
<body>
Go to <a href="b.html"> another page </a>
<form action="c.html">
name : <input type="text" name="name" value=""/> <br>
email : <input type="text" name="email" value=""/> <br>
<input type="submit" value="save"/>
</form>
</body>
打开它:
window.onbeforeunload = "Are you sure you want to leave?";
要关闭它:
window.onbeforeunload = null;
请记住,这不是正常事件 - 您无法以标准方式绑定它。
要检查值? 这取决于您的验证框架。
在jQuery中,这可能是(非常基本的例子):
$('input').change(function() {
if( $(this).val() != "" )
window.onbeforeunload = "Are you sure you want to leave?";
});
使用JQuery这个东西很容易做到。 因为你可以绑定到集合。
它不足以进行onbeforeunload,你只想触发导航,如果有人开始编辑东西。
要在Chrome和Safari中使用,您必须这样做
window.onbeforeunload = function (e) {
e = e || window.event;
var msg = "Sure you want to leave?";
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = msg;
}
// For Safari
return msg;
};
这是参考的一般规则
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE<8 and Firefox prior to version 4
if (e) {
e.returnValue = 'Any string';
}
// For Chrome, Safari, IE8+ and Opera 12+
return 'Any string';
};
参考:https://developer.mozilla.org/en/DOM/window.onbeforeunload
尝试这个:
<form action="c.html" onsubmit="window.onbeforeunload=function(){}">
尝试这个:
$(window).bind("beforeUnload", verify);
$("form").submit(function (){
$(window).unbind("beforeUnload");
};
试试这个: http : //cfsilence.com/blog/client/index.cfm/2009/10/12/jQuery-Method-To-Prompt-A-User-To-Save-Changes-Before-Leaving-Page
我在函数中添加了另一个位:
$('#submitButton').click(function () {
isDirty = false;
});
因此,当您想要提交时,表单不会要求验证:)
我希望这有帮助
注意:如果您不喜欢依赖于常用命名,您也可以执行类似$(“input [type = submit]”)的操作(否则您的提交按钮需要被称为submitButton)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.