我可以在单击锚标记时阻止调用onbeforeunload吗?

时间:2009-11-16 13:36:44

标签: javascript onbeforeunload

在头上:

<head>
    <script type="text/javascript">                          
        $(document).ready(function() {
            $("#anchor_id").click(clickHandler);
            window.onbeforeunload = confirmExit;
        });

        function clickHandler() {
            /* hide/show some hidden div's */
            $("body").append("<p>Hi there</p>");
        }

        function confirmExit() {
            return "There are some unsaved changes on page.";
        }
    </script>
</head>

身体:

<a id="anchor_id" href="javascript: void(0);">Click Me</a>

是否可以阻止调用onbeforeunload 在Internet Explorer中单击此链接时?其余的 在浏览器中,代码工作正常。

3 个答案:

答案 0 :(得分:1)

尝试设置href="#",并在clickHandler函数中返回false(或通过event.preventDefault()阻止默认事件)

答案 1 :(得分:0)

您可以使用jQuery的浏览器帮助程序将事件分配包装在条件浏览器逻辑中:

http://docs.jquery.com/Utilities/jQuery.browser.version

答案 2 :(得分:0)

试试这个,在FF3.5和IE8中测试

<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function()
            {
                $("#anchor_id").click(clickHandler);
                window.onbeforeunload = function()
                {
                    return "There are some unsaved changes on page.";
                };
            });

            function clickHandler()
            {
                /* hide/show some hidden div's */
                $("body").append("<p>Hi there</p>");
                return false;
            }
        </script>
    </head>
    <body>
        <a id="anchor_id" href="javascript: void(0);">Click Me</a>
    </body>
</html>