如果用户注意离开包含未保存设置的页面,我希望显示警告,但显然不是在他们尝试保存这些设置时。
我想我的理解是错误的,因为我认为下面应该有效,但事实并非如此。有人能告诉我我做错了什么吗?感谢。
$('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 '';
}
};
答案 0 :(得分: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');
});
答案 1 :(得分: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 '';
}
};
答案 2 :(得分:0)
Here is the perfect answer for your question.
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!';
}
}
};