开发者

Can I prevent onbeforeunload from being called when clicking on an anchor tag?

In head:

<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>

In body:

开发者_运维知识库
<a id="anchor_id" href="javascript: void(0);">Click Me</a>

Is it possible to prevent onbeforeunload from being called when clicking on this link in Internet Explorer? In the rest of the browsers the code is working fine.


Try setting href="#" instead, and return false in the clickHandler function (or prevent the default event by event.preventDefault())


You could wrap the event assignment in condition browser logic using jQuery's browser helper:

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


Try this, tested in FF3.5 and 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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜