首页 > 解决方案 > 用户离开页面之前的 JavaScript 确认,而不是页面加载

问题描述

我希望用户仅在离开页面以确认他们想要时看到警报。目前,我认为任何正在发生的事情也都在Page_Load显示警报。

我有这个代码:

window.onbeforeunload = confirmExit;
function confirmExit() {
    return "Changes you made may not be saved.";
}

预期:仅当退出或单击返回时显示确认警报。

实际:DropDownList我有导致警报显示以及离开页面。

编辑:

<asp:DropDownList ID="ddlJob" runat="server" AutoPostBack="true" CssClass="combobox" 
    DataTextField="name" DataValueField="name" OnClick="hideOnKeyPress(); return true;">
</asp:DropDownList>

标签: javascriptasp.net

解决方案


尝试这个:

 window.addEventListener('beforeunload', function (e) {
      // Cancel the event
      e.preventDefault();
      // Chrome requires returnValue to be set
      e.returnValue = 'Changes you made may not be saved.';
    });

推荐阅读