【问题标题】:jQuery confirmation of page leaving页面离开的jQuery确认
【发布时间】:2014-03-25 00:33:03
【问题描述】:

我尝试使用 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>

【问题讨论】:

    标签: javascript jquery warnings


    【解决方案1】:

    也许使用unbind 函数会更好?如下:

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

    【讨论】:

      【解决方案2】:

      您需要取消绑定 jQuery 处理程序,而不是本机 onbeforeunload 事件。所以使用:

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

      或者现在,首选方法是使用off()解绑:

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

      on() 用于绑定而不是bind()。请注意,尽管 bind()unbind() 并未被弃用,但仍然可以使用它。

      jsFiddle

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-03
        • 1970-01-01
        • 1970-01-01
        • 2011-11-09
        • 2019-06-09
        • 2018-02-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多