2012-07-17 88 views
3

我剥离与“document.location.hash”的网址,并试图检查当前网址留下什么。我不想使用任何插件,也不想从点击等触发事件中学习结果。需要立即和现代地学习网址变化。如何检测当前的网址当发生任何变化

的jQuery:

$(function() { 
    $(document).location().change(function() {//this part is not working 
     var anchor = document.location.hash; 
     if(anchor === '#one') { 
      alert('current url = #one'); 
     }else if (anchor === '#two') { 
      alert('current url = #two'); 
     }else if (anchor === '#three') { 
      alert('current url = #three'); 
     } 
     console.log(anchor); 
    }); 
}); 

HTML:

<a href="#one">one</a> 
<a href="#two">two</a> 
<a href="#three">three</a> 

深注:我已阅读这些问题和cout找到我在寻找: How to detect URL change in JavaScript + How to change the current URL in javascript?

回答

6

不使用比jQuery的其他插件,您可以处理 'hashchange' 事件:

$(document).ready(function() { 
    $(window).bind('hashchange', function(e) { 
    var anchor = document.location.hash; 
      if(anchor === '#one') { 
       alert('url = #one'); 
      }else if (anchor === '#two') { 
       alert('url = #two'); 
      }else if (anchor === '#three') { 
       alert('url = #three'); 
      } 
      console.log(anchor); 
    }); 
}); 

注意:Not all browsers support the hashchange event.

使用带后备:你应该use Modernizr to detect if hashchangeEvent is supported和如果支持检查失败,则回退到Ben Alman's jQuery hashchange event plugin,并在您的else块中使用@Baylor Rae的解决方案。

+2

取决于什么浏览器barlasapaydin想支持(http://caniuse.com/hashchange) – voigtan 2012-07-17 15:33:03

+0

完全..看到更新的答案 – BumbleB2na 2012-07-17 15:33:27

3

您可能会发现Ben Alman的jQuery hashchange event plugin很有帮助。

$(function(){ 

    // Bind the event. 
    $(window).hashchange(function(){ 
    // Alerts every time the hash changes! 
    alert(location.hash); 
    }); 

    // Trigger the event (useful on page load). 
    $(window).hashchange(); 

}); 
相关问题