JavaScript多页形式onbeforeunload问题

时间:2014-03-23 14:01:33

标签: javascript jquery

我正在使用多页形式jQuery脚本组成一个测验系统,我希望能够在尝试关闭页面时警告用户。我设法使用下面的代码做到这一点:

$(document).ready(function($) {
    window.onbeforeunload = function(){
        return 'Sure you want to close the page?';
    };
});

我的问题是,当我尝试提交表单并发布结果时,我会收到警告,询问我是否要离开此页面。这是代码:

$('#quizForm').formwizard({
    validationEnabled: true,
    focusFirstInput : true,
    formOptions: {
        beforeSubmit: window.onbeforeunload = null,
        resetForm: true
    }
});

我做错了什么?

LE:我创造了这个小提琴,也许有人可以帮助我,我的想法已经不多了。

http://jsfiddle.net/awLYY/5/

2 个答案:

答案 0 :(得分:0)

首先,您不需要等待DOM准备就绪以附加onbeforeunload处理程序。

第二,由于onbeforeunload是一个函数,你可以选择wither返回一个字符串,或者在你向服务器提交一些数据时不返回任何内容

var isFormBeingSubmitted = false;

window.onbeforeunload = function() {
    if( isFormBeingSubmitted ) {
        return;
    }
    return 'Sure you want to close the page?';
};

// now before you submit your form, just enable the isFormBeingSubmitted 
$('#quizForm').formwizard({
    validationEnabled: true,
    focusFirstInput : true,
    formOptions: {
        beforeSubmit: function() {
            isFormBeingSubmitted = true;
            return true;
        },
        resetForm: true
    }
});

答案 1 :(得分:0)

要回答我自己的问题,我所要做的就是添加到formwizard选项:

formPluginEnabled: true

现在一切正常。感谢