表单页面的离开确认

风行水上 @ 2014-09-12 19:00:48
标签:

    一个含有表单的页面,用户可能会意外点击链接而导致离开此页面,这时有可能导致表单中填写的数据丢失。

    下面的代码用于在用户离开当前页面时进行提示。如果是表单的提交动作,则不进行提示。

    (function(){
      var unload_check = true;
    
      $("form").submit(function(){
        unload_check = false;
      });
    
      window.addEventListener('beforeunload', function(evt){
        unload_check = true; // for the case submit does cause unload
        if(!unload_check) return;
    
        var message = 'You are on form editing page.\nLeave before submit may cause your data lost!';
        (evt || window.event).returnValue = message; // Important for cross browser
        return message;
      });
    })();
    
    标签:

      分享到:
      comments powered by Disqus

      17/18ms