【问题标题】:Stop User Leaving Before Postback (Javascript/ASP.NET)在回发之前停止用户离开 (Javascript/ASP.NET)
【发布时间】:2011-07-15 01:19:49
【问题描述】:

我有几个在回发上运行的函数,可能需要一点时间才能完成。

当启动回发时,我会显示带有此代码的加载图像:

function showLoader()
{
    document.getElementById("<%=loadingImage.ClientID%>").style.visibility="visible";
}

我希望能够向此函数添加代码,因此如果用户此时尝试离开,他们会被告知操作未完成。

我找到了这段代码:

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 = 'You sure you want to leave?'; //This is displayed on the dialog
    //e.stopPropagation works in Firefox.
    if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
}
window.onbeforeunload=goodbye;

这可行,但我只希望代码在加载图像处于活动状态时处于活动状态。

我尝试了以下方法,但当页面最终回发时它会显示警报消息:

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 = 'You sure you want to leave?'; //This is displayed on the dialog
    //e.stopPropagation works in Firefox.
    if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
}
function showLoader()
{
    document.getElementById("<%=loadingImage.ClientID%>").style.visibility="visible";
    window.onbeforeunload=goodbye;
}

有什么想法可以调整它以仅在用户离开页面时显示而不是在回发完成时显示?

【问题讨论】:

    标签: javascript asp.net


    【解决方案1】:

    您需要在提交表单时将window.onbeforeunload 设置为null。所以,基本上:

    <form onsubmit="window.onbeforeunload=null">
    

    要动态地将其应用于所有表单,我建议为此编写一个 window.onload 函数,它无需编辑所有页面上的每个表单。

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多