开发者

onhashchange with IE 9

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 noth开发者_如何学JAVAing happens.

Any ideas?


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


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


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜