onhashchange with IE 9

2020-03-25 14:46发布

I have the following code

$(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;
}

I click a link that changes the hash and in all other browsers I get the alert in test

However in IE I get the first alert saying it supports onhashchange but then when the hash changes nothing happens.

Any ideas?

3条回答
干净又极端
2楼-- · 2020-03-25 15:37

See this: link

Does the browser support window.onhashchange?

Note that IE8 running in IE7 compatibility mode reports true for 'onhashchange' in window, even though the event isn't supported, so also test document.documentMode.

var docmode = document.documentMode;
if ('onhashchange' in window && (docmode === undefined || docmode > 7 )) {
    window.onhashchange = checkHash;
}
查看更多
贪生不怕死
3楼-- · 2020-03-25 15:38

There's an example on the MSDN doc page.

Basically, I removed all the extra "map" stuff on their page and the only difference between theirs and your example is that they include the following meta-tag:

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

I added this to the head tag in your example and it worked fine.

This meta-tag basically says to run the page as if it were in IE 8 and not IE 9 (which is still in beta).

For more information on this meta-tag read here

查看更多
够拽才男人
4楼-- · 2020-03-25 15:40

The new hashchange event in HTML5 is supported by all current browsers; no need to fool your browser into thinking it's IE8.

This code works in IE 9, FF 5, Safari 5, and Chrome 12 on Win 7:

<!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>
查看更多
登录 后发表回答