onhashchange with IE 9

為{幸葍}努か 提交于 2019-12-19 09:26:48

问题


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?


回答1:


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




回答2:


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:


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>


来源:https://stackoverflow.com/questions/4984319/onhashchange-with-ie-9

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