当离开页面时,使用'onbeforeunload'显示警告,除非点击了'Submit'。

8
我希望在用户尝试离开包含未保存设置的页面时显示警告,但如果他们试图保存这些设置,则不需要显示警告。
我想我的理解是错误的,因为我认为下面的代码应该可以工作,但实际上并不能。有人能告诉我我做错了什么吗?谢谢。
$('input[name="Submit"]').off('onbeforeunload');

window.onbeforeunload = function closeEditorWarning(){

    /** Check to see if the settings warning is displayed */
    if($('#unsaved-settings').css('display') !== 'none'){
        bol_option_changed = true;
    }

    /** Display a warning if the user is trying to leave the page with unsaved settings */
    if(bol_option_changed === true){
        return '';
    }


};
4个回答

18

您可以使用jQuery的.on()来设置onbeforeunload事件,然后在表单提交时使用.off()方法

// Warning
$(window).on('beforeunload', function(){
    return "Any changes will be lost";
});

// Form Submit
$(document).on("submit", "form", function(event){
    // disable unload warning
    $(window).off('beforeunload');
});

1
优秀的答案。比设置标志位更容易。 - Moe
所以我实现了这个解决方案,它运行得很好。但是Chrome刚刚发布了一个更新,改变了beforeunload的处理方式。它不再支持自定义消息。而且,如果你返回任何东西,包括"false",它都会显示消息。所以我的真正解决方案是将这个与在函数末尾删除我的"return false"结合起来。 - danielson317

5
你可以尝试这样做:在单击提交按钮时设置一个标志,并使用此标志来检查用户是否已经点击了提交或在半途离开了页面。
伪代码:
var submit_clicked = false;

$('input[type="submit"]').click(function(){
    submit_clicked = true;
});


window.onbeforeunload = function closeEditorWarning () {

  /** Check to see if the settings warning is displayed */
  if(($('#unsaved-settings').css('display') !== 'none') && 
      submit_clicked === false) {
    bol_option_changed = true;
  }

  /** Display a warning if the user is trying to leave the page with unsaved settings */
  if(bol_option_changed === true){
    return '';
  }


};

好的想法,但可悲的是它并没有起作用。点击事件首先被捕获了,但警告仍然显示。谢谢。 - David Gard
我需要在 onbeforeunload 函数中添加 var bol_option_changed = false;,现在一切都正常了。谢谢。 - David Gard

0
我遇到了这个问题,所以我想分享我的解决方案。 Brent White的解决方案对我不起作用,因为我使用了jQuery-validation插件。这意味着如果用户提供了无效的输入,即使他们点击提交按钮,他们仍然会停留在页面上。此时,如果他们离开或刷新页面,警报消息将不会显示。
$(window).bind('beforeunload', function(evt) {
  var isSubmitButton = (evt.srcElement.activeElement.type === "submit");
  var isModified = ($form.data("isModified") === true); 
  if ( !isSubmitButton && isModified) {
    return "You need to save your changes before you leave the page";
  } 
});  

0

这里是你问题的完美答案。

document.querySelector('.send').addEventListener("click", function(){ // put a class="send" in submit button
    window.btn_clicked = true; // if it is click onbeforeunload will not add dialog anymore
});
window.onbeforeunload = function(){

      if(!window.btn_clicked){
          var lot = $('#lot_no').val(); //getting values from form
      if(!lot == ''){  //checking if it is not empty
        return 'Changes you made not be saved!';
      }

      }


};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接