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

拥有回忆 提交于 2019-12-08 13:28:45

问题


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.


回答1:


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




回答2:


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

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




回答3:


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>


来源:https://stackoverflow.com/questions/1742241/can-i-prevent-onbeforeunload-from-being-called-when-clicking-on-an-anchor-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!