【问题标题】:onhashchange with IE 9onhashchange 与 IE 9
【发布时间】:2011-02-13 13:11:55
【问题描述】:

我有以下代码

$(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,但是当哈希更改时,什么都没有发生。

有什么想法吗?

【问题讨论】:

    标签: internet-explorer hashchange


    【解决方案1】:

    看到这个:link

    浏览器是否支持window.onhashchange?

    请注意,在 IE7 兼容模式下运行的 IE8 在窗口中报告“onhashchange”为 true, 即使不支持该事件,也要测试document.documentMode

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

    【讨论】:

      【解决方案2】:

      在 MSDN 文档page 上有一个示例。

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

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

      我在您的示例中将其添加到 head 标记中,并且效果很好。

      这个元标记基本上表示要像在 IE 8 中而不是在 IE 9(仍处于测试阶段)中一样运行页面。

      有关此元标记的更多信息,请阅读here

      【讨论】:

        【解决方案3】:

        当前所有浏览器都支持 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>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-08-05
          • 2014-11-06
          • 2016-01-04
          • 2017-10-27
          • 2014-01-08
          • 2013-05-12
          • 1970-01-01
          相关资源
          最近更新 更多