离开页面时显示带有'onbeforeunload'的警告,除非单击"提交"

Dav*_*ard 6 javascript onbeforeunload

如果用户注意离开包含未保存设置的页面,我希望显示警告,但显然不是在他们尝试保存这些设置时.

我想我的理解是错误的,因为我认为下面应该有效,但事实并非如此.有人能告诉我我做错了什么吗?谢谢.

$('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 '';
    }


};
Run Code Online (Sandbox Code Playgroud)

小智 11

您可以使用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');
});
Run Code Online (Sandbox Code Playgroud)


pal*_*dot 5

您可以尝试:在单击“提交”按钮时设置一个标志,并使用该标志检查用户是否单击了“提交”或中途离开页面

伪代码:

var submit_clicked = false;

$('input[name="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 '';
  }


};
Run Code Online (Sandbox Code Playgroud)