简体   繁体   English

jQuery确认页面离开

[英]jQuery confirmation of page leaving

I tried to use jQuery serialize to confirm user for form content change. 我试图使用jQuery序列化来确认用户是否需要更改表单内容。 It seems working. 似乎有效。 The issue is that before I submit the form, I reset the window.onbeforeload to null and hope it will not popup the confirmation dialog when user clicks submit button. 问题在于,在提交表单之前,我将window.onbeforeload重置为null,希望当用户单击“提交”按钮时,它不会弹出确认对话框。 But my code below still show the popup when submit button clicked. 但是当我单击提交按钮时,下面的代码仍然显示弹出窗口。

<!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>

Maybe it'll be better to use unbind function? 也许使用unbind功能会更好? Like following: 如下所示:

$("#form").submit( function() {
  alert("called submit");
  window.unbind('beforeunload')
});

You need to unbind the jQuery handler, not the native onbeforeunload event. 您需要取消绑定jQuery处理程序,而不是本机onbeforeunload事件。 So use: 因此使用:

$(window).unbind('beforeunload');

Or now, preferred method is to use off() to unbind: 或者现在,首选方法是使用off()解除绑定:

$(window).off('beforeunload');

And on() for binding instead of bind() . 并且on()用于绑定,而不是bind() Be aware though that bind() and unbind() aren't deprecated, it's still ok to use it. 请注意,虽然不建议使用bind()unbind() ,但仍然可以使用它。

jsFiddle 的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM