2013-01-15 43 views
6

我希望在用户离开包含未保存设置的页面时显示警告,但如果他们试图保存这些设置。离开页面时显示“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 ''; 
    } 


}; 

回答

3

你可以试试这个:设置一个标志,当点击提交按钮,并使用该标志,检查是否用户点击提交或离开页面中途

伪代码:

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


}; 
+0

好想法,但可悲的是它不工作。点击正在被拾起,但警告仍在显示。谢谢。 –

+0

我需要将'var bol_option_changed = false;'添加到'onbeforeunload'函数,所以它现在都在工作。谢谢。 –

7

你可以使用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'); 
}); 
+0

优秀的答案。比设置标志更容易。 – Moe

+0

所以我实现了这个解决方案,它工作得很好。但是Chrome刚发布了一个更新,改变了beforeunload的处理方式。它不再支持自定义消息。此外,如果您返回任何内容(包括“false”),它将显示该消息。所以我真正的解决方案是这个组合,并在我的函数结束时删除我的“返回false”。 – danielson317

0

我遇到了这个问题,所以我想分享我的解决方案。

Brent White的解决方案对我无效,因为我使用了jQuery验证插件。这意味着如果用户提供无效输入,即使他们点击提交按钮后,他们仍然会留在页面上。此时,如果他们离开或刷新页面,警告消息将不会显示。

$(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"; 
    } 
}); 
相关问题