2012-07-17 89 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(); 

}); 
相關問題