[英]jQuery confirmation of page leaving
我试图使用jQuery序列化来确认用户是否需要更改表单内容。 似乎有效。 问题在于,在提交表单之前,我将window.onbeforeload重置为null,希望当用户单击“提交”按钮时,它不会弹出确认对话框。 但是当我单击提交按钮时,下面的代码仍然显示弹出窗口。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery warn page leaving</title>
<link rel="stylesheet" href="../jquery-ui-1.10.4.custom/css/smoothness/jquery-ui-1.10.4.custom.css">
<script src="../jquery-ui-1.10.4.custom/js/jquery-1.10.2.js"></script>
<script src="../jquery-ui-1.10.4.custom/js/jquery-ui-1.10.4.custom.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(document).ready(function(){
$('#form').data('serialize',$('#form').serialize());
}
);
$(window).bind('beforeunload', function(e){
if($('#form').serialize()!=$('#form').data('serialize'))
return "Data changed.";
else e=null;
// i.e; if form state change show box not.
});
$("#form").submit( function() {
alert("called submit");
window.onbeforeunload = null;
});
function disableBeforeUnload() {
alert ("call disable func");
window.onbeforeunload = null;
}
</script>
</head>
<body>
<a href="http://www.google.com">Go to google</a>
<form id="form" name='experiment' action="#" onsubmit="disableBeforeUnload();">
<Label for='firstName'>First name: </label><input name = 'fname' type="text" size="30" />
<Label for='firstName'>Last name: </label><input name = 'lname' type="text" size="30" />
<select name ='options'>
<option value=1> One</option>
<option value=2> two</option>
<option value=3> three</option>
</select>
<button type="submit" name="submit" />
</form>
</body>
</html>
也许使用unbind
功能会更好? 如下所示:
$("#form").submit( function() {
alert("called submit");
window.unbind('beforeunload')
});
您需要取消绑定jQuery处理程序,而不是本机onbeforeunload事件。 因此使用:
$(window).unbind('beforeunload');
或者现在,首选方法是使用off()
解除绑定:
$(window).off('beforeunload');
并且on()
用于绑定,而不是bind()
。 请注意,虽然不建议使用bind()
和unbind()
,但仍然可以使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.