如何确定页面何时退出是因为表单提交?

时间:2016-09-06 13:41:38

标签: javascript jquery html confirm

这是我的代码:

// confirm alert before close page
window.onbeforeunload = function(evt) {
    var el = document.getElementById("qandatextarea");
    if( el && el.value && !DontAskBeforeExit){
        var message = 'are you sure you want to exit this page?';
        if (typeof evt == 'undefined') {
            evt = window.event;
        }
        if (evt) {
            evt.returnValue = message;
        }

        return message;
    }
}

请关注这一行:

if( el && el.value && !DontAskBeforeExit){

有三个条件:

  • el:检查DOM中是否存在textarea?

  • el.value:检查该textarea的值是多少? (换句话说,textarea是空的吗?)

  • !DontAskBeforeExit:它是一个01的变量。当该textarea的内容存储到localStorage时,它为1,否则为0

好的,现在我还需要一个条件。我需要检查"是提交还是退出的页面"?我的意思是,如果用户发送帖子(提交),我不需要显示弹出提醒。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

// set a flag so teh function isn't called twice on the form submit
var formsubmitted = false;

document.getElementById('myform').onsubmit = function(evt){
    formsubmitted = true;
    exitPage(evt, "formsubmit");
};

window.onbeforeunload = function(evt){
    // we don't want this to fire twice when the form is submitted
    if(!formsubmitted) exitPage(evt, "naturalunload");
}

// added an extra parameter , name, and condition to your original function
function exitPage(evt, exitType) {
    var el = document.getElementById("qandatextarea");
    if( el && el.value && !DontAskBeforeExit && exitType=="formsubmit"){
        var message = 'are you sure you want to exit this page?';
        if (typeof evt == 'undefined') {
            evt = window.event;
        }
        if (evt) {
            evt.returnValue = message;
        }

        return message;
    }
}