我试图使用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')
});

关于javascript - jQuery确认页面离开,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21969250/

10-15 08:23