【问题标题】:jQuery - hashchange eventjQuery - hashchange 事件
【发布时间】:2011-03-06 15:37:26
【问题描述】:

我正在使用:

$(window).bind( 'hashchange', function(e) { });

将函数绑定到哈希更改事件。这似乎在 IE8、Firefox 和 Chrome 中有效,但在 Safari 中无效,我认为在早期版本的 IE 中无效。对于这些浏览器,我想禁用使用哈希和hashchange 事件的 JavaScript 代码。

jQuery 有没有一种方法可以检测浏览器是否支持hashchange 事件?也许是jQuery.support...

【问题讨论】:

  • jQuery hashchange event - jQuery 插件完美运行,即使在 IE8 中也是如此。 + 使用起来非常简单 :)

标签: javascript jquery hashchange browser-state


【解决方案1】:

您可以通过以下方式检测浏览器是否支持该事件:

if ("onhashchange" in window) {
  //...
}

另见:

【讨论】:

  • 感谢您的快速回复。
  • 请注意,在 IE7 兼容模式下运行的 IE8 会在窗口中报告“onhashchange”为真,即使该事件不受支持 - 来自 jQuery Mobile
【解决方案2】:

截至 2017 年的更新答案是,如果有人需要,onhashchange 在所有主要浏览器中都得到了很好的支持。有关详细信息,请参阅caniuse。使用 jQuery 不需要插件:

$( window ).on( 'hashchange', function( e ) {
    console.log( 'hash changed' );
} );

我偶尔会遇到仍在使用 hashbang URL 的遗留系统,这很有帮助。如果您正在构建新内容并使用哈希链接,我强烈建议您考虑改用 HTML5 pushState API。

【讨论】:

  • 这个很好用,使用window.location.hash访问当前哈希。
【解决方案3】:

有一个 hashchange 插件,它封装了功能和跨浏览器问题available here

【讨论】:

  • 只有
【解决方案4】:

解决问题的不同方法...

有 3 种方法可以将 hashchange 事件绑定到方法:

<script>
    window.onhashchange = doThisWhenTheHashChanges;
</script>

或者

<script>
    window.addEventListener("hashchange", doThisWhenTheHashChanges, false);
</script>

或者

<body onhashchange="doThisWhenTheHashChanges();">

这些都适用于 Win 7 上的 IE 9、FF 5、Safari 5 和 Chrome 12。

【讨论】:

    【解决方案5】:

    试试 Mozilla 官方网站:https://developer.mozilla.org/en/DOM/window.onhashchange

    引用如下:

    if ("onhashchange" in window) {
        alert("The browser supports the hashchange event!");
    }
    
    function locationHashChanged() {
        if (location.hash === "#somecoolfeature") {
            somecoolfeature();
        }
    }
    
    window.onhashchange = locationHashChanged;
    

    【讨论】:

      【解决方案6】:

      我刚刚遇到了同样的问题(IE7 中缺少 hashchange 事件)。适合我的目的的解决方法是绑定哈希更改链接的点击事件。

      <a class='hash-changer' href='#foo'>Foo</a>
      
      <script type='text/javascript'>
      
      if (("onhashchange" in window) && !($.browser.msie)) { 
      
          //modern browsers 
          $(window).bind('hashchange', function() {
              var hash = window.location.hash.replace(/^#/,'');
              //do whatever you need with the hash
          });
      
      } else {
      
          //IE and browsers that don't support hashchange
          $('a.hash-changer').bind('click', function() {
              var hash = $(this).attr('href').replace(/^#/,'');
              //do whatever you need with the hash
          });
      
      }
      
      </script>
      

      【讨论】:

      • 您可以使用$('a[href^="#"]') 获取以哈希开头的hrefs 的链接,从而避免添加类
      【解决方案7】:

      请注意,在 IE 7 和 IE 9 的情况下,if 语句将为 ("onhashchange" in windows) 但 window.onhashchange 永远不会触发,因此最好存储散列并在每 100 毫秒后检查它是否所有版本的 IE 都更改或不更改。

          if (("onhashchange" in window) && !($.browser.msie)) { 
               window.onhashchange = function () { 
                    alert(window.location.hash);             
               }            
               // Or $(window).bind( 'hashchange',function(e) {  
               //       alert(window.location.hash); 
               //   });              
          }
          else { 
              var prevHash = window.location.hash;
              window.setInterval(function () {
                 if (window.location.hash != prevHash) {
                    prevHash = window.location.hash;
                    alert(window.location.hash);
                 }
              }, 100);
          }
      

      【讨论】:

      • 这对浏览器来说是不是太多了?每 100 毫秒轮询一次哈希更改?
      • 您的示例代码使我的 IE8 一直处于警报状态,直到我打开任务管理器并终止进程:)
      • 那是因为有一个错字,而不是“storedHash”使用“prevHash”,它会工作。他基本上使用了与声明方式不同的变量名。
      【解决方案8】:

      如果使用不同的方式而不是散列事件并听popstate之类的呢。

      window.addEventListener('popstate', function(event)
      {
          if(window.location.hash) {
                  var hash = window.location.hash;
                  console.log(hash);
          }
      });
      

      这种方法在我目前尝试过的大多数浏览器中都能正常工作。

      【讨论】:

      • Popstate 甚至比 hashchange 更新。例如,IE
      【解决方案9】:

      这个小巧的 jQuery 插件使用起来非常简单:https://github.com/finnlabs/jquery.observehashchange/

      【讨论】:

        【解决方案10】:

        我认为 Chris Coyier 有解决该哈希问题的方法,看看他的截屏视频:

        Best Practices with Dynamic Content

        【讨论】:

        • 谢谢,我会调查的。
        【解决方案11】:

        使用Modernizr 检测功能。一般来说,jQuery 提供检测浏览器功能:http://api.jquery.com/jQuery.support/。但是,hashchange 不在列表中。

        wiki of Modernizr 提供了一个库列表,用于向旧浏览器添加 HTML5 功能。 list for hashchange 包含一个指向项目 HTML5 History API 的指针,如果您想模拟旧浏览器中的行为,它似乎提供了您需要的功能。

        【讨论】:

          【解决方案12】:

          这是@johnny.rodgers 的更新版本

          希望能帮助别人。

          // ie9 ve ie7 return true but never fire, lets remove ie less then 10
          if(("onhashchange" in window) && navigator.userAgent.toLowerCase().indexOf('msie') == -1){ // event supported?
              window.onhashchange = function(){
                  var url = window.location.hash.substring(1);
                  alert(url);
              }
          }
          else{ // event not supported:
              var storedhash = window.location.hash;
              window.setInterval(function(){
                  if(window.location.hash != storedhash){
                      storedhash = window.location.hash;
                      alert(url);
                  }
              }, 100);
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-04-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多