在IE9中,onbeforeunload事件过于活跃

onbeforeunload event is too enthusiastic in IE9

本文关键字:于活跃 活跃 事件 IE9 onbeforeunload      更新时间:2023-09-26

下面是一些示例测试html:

<!DOCTYPE html>
<html>
  <body>
    <a href="javascript:alert('Not going anywhere!');">Go nowhere 1</a>
    <a href="javascript:void(0);" onclick="alert('Not going anywhere!');">Go nowhere 2</a>
    <a href="http://www.google.com">Go somewhere</a>
    <script type="text/javascript">
      window.onbeforeunload = function() { return "Really leave?"; };
    </script>
  </body>
</html>

这是一个工作页面:timjeanes.com/ie9_onbeforeunload.htm

在Firefox, Chrome和Safari中,我得到我想要的行为。也就是说,单击前两个链接中的任何一个都会显示一个警告对话框;点击第三个链接(或其他导航方式)会显示"您确定要离开这个页面吗?"的信息。

然而,在IE9中,当你点击前两个链接中的任何一个时,"你确定要离开这个页面吗?"消息也会显示出来,即使没有导航发生——我们只是在运行一些javascript。

我做错了什么吗?或者IE有一个很好的解决方案?

一个选项是使用href="#",并把我的javascript在onclick。我不喜欢这样,因为它会把用户带到页面的顶部,而我现实生活中的页面相当高。

我没有在其他版本的IE中测试过

这是一个非常不幸的错误。似乎您必须绕过它,使用哈希链接方法可能是最好的方法。为避免将用户带到页面顶部,请使用event.preventDefault()event.returnValue = false取消该事件。

function myClickHandler(e) {
    if (e.preventDefault)
        e.preventDefault();
    e.returnValue = false;
    alert("Not going anywhere!");
}

这样写:

<a href="#" onclick="myClickHandler(event)">Go nowhere 1</a>

编辑:你可以像这样取消你页面上所有哈希链接的事件:

var links = document.links;
for (var i = 0; i < links.length; i++) {
    var link = links[i];
    if (link.href == "#") {
        if (link.addEventListener) {
            link.addEventListener("click", cancelEvent, false);
        }
        else if (link.attachEvent) {
            link.attachEvent("onclick", cancelEvent);
        }
    }
}
function cancelEvent(e) {
    e = e || window.event;
    if (e.preventDefault)
        e.preventDefault();
    e.returnValue = false;
}

或者使用jQuery只使用一行代码:

$("a[href='#']").click(function (e) { e.preventDefault(); });

一个更简单的解决方案是在IE中使用onunload,在其他浏览器中使用onbeforeunload

href中的#null防止页面跳转而不仅仅是#onclick=""中的脚本

你不应该使用href="javascript:...来绑定事件:下面是不好的

<a href="javascript:alert('Not going anywhere!');">Go nowhere 1</a>

如果你要使用onclick并使href无效,那么只需在onclick中返回false。

<a onclick="alert('Not going anywhere!');return false;">Go nowhere 2</a>

当你点击第一个链接时弹出"你确定要离开这个页面吗?"这实际上不是一个bug;这似乎是ie9的一个"特性"——我不喜欢IE的更多原因