window.onbeforeunload没做你想做的事

时间:2014-03-05 11:19:03

标签: javascript

如果用户通过关闭选项卡卸载屏幕,我试图使用window.onbeforeunload方法删除一堆会话变量。 这是我的功能:

    <script type="text/javascript">
    window.onbeforeunload = function (e) {
        return 'Are you sure you want to leave this page?  You will lose any unsaved data.';
        document.getElementById('<%=btnFinshed%>').click();
        return null;
    };  
</script>  

我添加了返回消息,只是为了查看它是否正在触发,但它更令人困惑。我没有显示我的消息,而是(在Mozilla上):

此页面要求您确认是否要离开 - 您输入的数据可能无法保存。

IE做了类似的事情。

我的btnFinshed_click没有触发,无论我是否输入了我的消息,随后保留需要删除的会话变量会导致错误。

有什么想法吗?

行。我添加了另一个按钮和另一个javascript函数,只是为了测试这个document.getElementById命令。结果是document.getElementById肯定不起作用。这是例程:

    <script  language="javascript" type="text/javascript">
       function testThis(e) {
           var element1 = document.getElementById('<%=btnFinished%>');
           if (element1 != null) {
               alert("element is found");
               //code to set the value variable.
               document.getElementById('<%=btnFinished%>').fireEvent("onclick");
           }
           else {
               alert("element is null");
           }
           return false;
       };
</script>  

    <asp:Button ID="Button1" runat="server" Text="X" OnClientClick="testThis()" />

    <asp:Button ID="btnFinished" runat="server" Text="Finished" onclick="btnFinshed_Click" CausesValidation="False" /> - i renamed this button too.

结果 - document.getElementById不起作用。元素显然在那里。 id很明显是正确的。 javascript命令必须是duff。

1 个答案:

答案 0 :(得分:0)

试试这个:

window.onbeforeunload = function (e) {
    var e = e || window.event,
        msg = 'Are you sure you want to leave this page?  You will lose any unsaved data.';
    if (e) {
        e.returnValue = msg;
    }
    return msg;
};
相关问题