通过防止窗口事件问题防止双重提交

Prevent double submission with prevent window event issue

本文关键字:提交 问题 窗口 事件      更新时间:2024-02-11

我使用以下函数来防止双重提交:

$("#form").submit(function () {  
    var form = $(this);  
    form.find("input[type=submit]").attr("disabled", "disabled")  
    form.find("input[type=submit]").attr("value", "Processing");  
  });

它工作正常,但我有以下代码,它会触发警报以避免意外离开页面:

function goodbye(e) {
     if(!e) e = window.event;
    //e.cancelBubble is supported by IE - this will kill the bubbling process.
    e.cancelBubble = true;
    e.returnValue = '¿DO YOU REALLY WANT TO LEAVE THIS PAGE?'; //This is displayed on the dialog
//e.stopPropagation works in Firefox.
    if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
}
window.onbeforeunload=goodbye;

问题是,如果用户点击提交,意识到他不想离开页面,而是点击留在这个页面上,提交按钮仍然被禁用。

单击此页面上的"停留"后,如何重新启用它?

谢谢!

按钮问题

你想禁用和启用提交按钮,这样你就知道你要触摸同一种功能和对象两次,最好在功能中利用这一点

function disableSubmit(form, enabled){
    var submit = form.find("input[type=submit]"),
        dataVar = enabled !== true ? "processing-message" : "send-message",
        message = submit.data(dataVar);
    submit.prop('disabled', (enabled !== true) );
    submit.val(message);
}

我可以在每个表单上使用它,使其更加通用。但按钮中的消息将显示您在数据属性中输入的任何内容。

取消提交

取消加载前事件时出现问题;它没有回调。我提供的解决方案是使用超时。由于你不知道对方是否取消,我认为2秒就足够提交页面了。您必须有2秒的耐心才能再次启用提交按钮。但你可以随心所欲地调整它当然是

if (e.stopPropagation) {
    setTimeout(function () {
        disableSubmit(formObject, true);
    }, 2000);
    e.stopPropagation();
    e.preventDefault();
}

JSFiddle示例