IE 9中的onhashchange

3
我有以下代码。
$(document).ready(function() {
   if ("onhashchange" in window) {
      alert("The browser supports the hashchange event!");
   }
   function test(){
  alert("hash has changed = " + window.location.hash)
   }
   window.onhashchange =test;
}

我点击一个链接改变了网址的哈希部分,在其他所有浏览器中我能看到test的弹窗提示。

但是在IE浏览器中,我会收到第一个弹窗提示,它表示支持onhashchange事件,但是当哈希部分发生改变时,没有任何反应。

有什么想法吗?

3个回答

2

请看这个:链接

浏览器是否支持window.onhashchange?

请注意,即使该事件不受支持,运行在IE7兼容模式下的IE8在window中报告'onhashchange'为true,因此还要测试document.documentMode

var docmode = document.documentMode;
if ('onhashchange' in window && (docmode === undefined || docmode > 7 )) {
    window.onhashchange = checkHash;
}

1

HTML5中的新hashchange事件由所有当前浏览器支持,无需让您的浏览器认为它是IE8。

此代码适用于Win 7上的IE 9、FF 5、Safari 5和Chrome 12:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <script>
            window.onhashchange = doThisWhenTheHashChanges;

            function changeTheHash()
            {
                var newHashValue = document.getElementById("newHashInput").value;
                var currentLocation = window.location.pathname;
                window.location.hash = newHashValue;
            }

            function doThisWhenTheHashChanges()
            {
                alert("The hash has changed!");
            }
        </script>
    </head>
    <body> 
        <h1>Hash Change Test</h1>
        <form>
            <input type="text" id="newHashInput" autofocus>
            <input type="button" value="Set" onclick="changeTheHash()">
        </form>
    </body>
</html>

1

MSDN文档页面上有一个示例。

基本上,我删除了他们页面上所有额外的“map”内容,他们和你的示例之间唯一的区别是他们包含以下元标签:

<meta http-equiv="X-UA-Compatible" content="IE=8" >

我在你的示例中添加了这个标签到头部,它可以正常工作。

这个元标签基本上是告诉页面以 IE 8 的方式运行,而不是 IE 9(它仍处于测试版)。

如需更多关于此元标签的信息,请阅读这里


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接