简体   繁体   English

setTimeout(x,0)在Chrome中不延迟

[英]setTimeout(x, 0) not delaying in Chrome

I have a web page with a form on it; 我有一个带有表格的网页; I want to warn the user if they move away. 如果用户离开,我想警告他们。 I haven't implemented dirty checking so my onbeforeunload code is simply 我还没有实现脏检查,所以我的onbeforeunload代码很简单

window.onbeforeunload = function () {
    return 'message'
};

I don't want this warning when they submit the form, so I remove the event on submit. 他们提交表单时,我不希望收到此警告,因此我在提交时删除了该事件。 However, the submit may fail , so I need to put the event back afterwards (so if they then navigate away they still get warned). 但是,提交可能会失败 ,因此我需要在事后将事件放回原处(因此,如果他们随后离开,他们仍然会收到警告)。 To that end I have done the following: 为此,我做了以下工作:

var tempDisableBeforeUnload = function() {
    var obu = window.onbeforeunload;
    if (obu) {
        window.onbeforeunload = null;
        setTimeout(function() {
            window.onbeforeunload = obu;
        }, 0);
    }
}
$("form.noWarnOnSubmit").submit(tempDisableBeforeUnload);

This works fine in Firefox and IE - the setTimeout(x, 0) defers the restoration of the event handler until after the submit has decided whether it is successful or not . 这在Firefox和IE中可以正常工作setTimeout(x, 0)推迟事件处理程序的恢复,直到submit决定成功与否之后

However, in Chrome, the timeout appears to occur immediately, and I get the warning when I submit my form. 但是,在Chrome中,超时似乎立即发生,并且在提交表单时收到警告。

How can I make this work on Chrome, or how else can I achieve the end of "don't warn on submit, but put the warning back if the submit fails"? 如何在Chrome上执行此操作,或者如何才能达到“不要警告提交,但如果提交失败,请放回警告”的结尾?

Cant you do the following: 不能执行以下操作:

var unloadActive = true;
window.onbeforeunload = function () {
    if(unloadActive) return 'message'
};
$("form.noWarnOnSubmit").submit(function(event){
    unloadActive = false;
    // do all your checks and things, whatever, and if the checks fail:
    unloadActive = true;
});

Then you don't need to do all that function juggling which might cause issues. 然后,您无需进行所有可能导致问题的功能处理。 I haven't tested this, but this is how I would do it. 我还没有测试过,但这就是我要做的。

I have overcome my immediate issue by 我已经克服了我眼前的问题

  • Binding my event to fire after the jQuery validation event, by deferring my submit event binding: 通过推迟我的submit事件绑定,将我的事件绑定到jQuery验证事件之后触发:
$(function() {
    $("form.noWarnOnSubmit").submit(disableBeforeUnloadIfNotCancelled);
});
  • Changing my event handler to only unbind the onbeforeunload event if the submit event is cancelled. 将我的事件处理程序更改为仅在submit事件被取消的情况下才取消绑定onbeforeunload事件。
var disableBeforeUnloadIfNotCancelled = function (e) {
    if (!e.isDefaultPrevented()) {
        window.onbeforeunload = null;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM