2012-08-15 195 views
1

我使用這個代碼知道什麼是url中#符號後:檢測#符號後的URL變化

var a = document.URL.split("#")[1]; 

例如,如果網頁的網址是http://example.com/path/to/somewhere/#contentpart,可變a將包含contentpart

但問題是,用戶可以點擊指向同一個頁面,但另一部分(例如:<a href="#footer">Go to footer</a>)的鏈接,如果是這樣,頁面將重裝。 (只是頁面將導航到其他地方)

我的問題是,如何檢測何時#在#登錄相同的頁面後更改URL?

歡迎任何javascript/jQuery方法。

+1

'window.location.hash'不夠酷嗎? – 2012-08-15 22:40:54

+0

@webarto我不知道JavaScript中有這樣的東西:)謝謝! – 2012-08-15 22:42:09

+1

你一定在開玩笑吧。 – 2012-08-15 22:42:24

回答

4

我建議,在考慮當前的代碼:

$(window).on('hashchange', function(e){ 
    var newHash = document.href.split('#')[1]; 
}); 

雖然這是一個比較容易簡單地使用:

$(window).on('hashchange', function(e){ 
    var newHash = document.location.hash; 
    console.log(newHash); 
}); 

JS Fiddle demo

如果你不希望散列包括#字符,然後使用來代替:

$(window).on('hashchange', function(e){ 
    var newHash = document.location.hash.substring(1); 
    console.log(newHash); 
}); 

JS Fiddle demo

+0

謝謝,它的工作!一個問題:'document.location.hash'返回'#contentpart'而不是'contentpart'。如何從結果中刪除'#'? – 2012-08-15 22:45:13

+1

@MahdiGhiasi'.replace('#','');' – 2012-08-15 22:45:51

+1

@MahdiGhiasi:是的,對不起,我剛剛開始使用'substring()'(如在最後的代碼塊中),儘管'replace()'當然是有效的。 – 2012-08-15 22:47:08

2

您可以通過在所有現代瀏覽器越來越window.location

var a = window.location.hash; 

變化的hash屬性這個屬性火hashchange事件而得到URL哈希值。 MDN文章中提供了IE7及以下版本的解決方法。

window.onhashchange = function (e) { 
    // Manage changes to your page 
    // You can also inspect e.newURL and e.oldURL if you need to 

    // Optionally prevent window from scrolling to target 
    e.preventDefault(); 
} 

如果您使用的是jQuery,請查看jQuery BBQ。它包含了許多怪癖和瀏覽器兼容性問題,還允許您將更改推送到URL /歷史記錄狀態,而不是依賴用戶單擊鏈接。

+0

感謝您使用純JavaScript方法。正如webarto在評論中所說,jQuery並非一切!但是,建議的方法和該jQuery方法的性能有什麼區別? – 2012-08-15 22:59:45

+0

與原生DOM方法相比,jQuery事件綁定總是有更多的開銷......但是不值得擔心:如果你已經在頁面上有了jQuery,就使用它。 jQuery方法對於我的示例代碼還有一個額外的好處,那就是使用'on'可以綁定和管理多個事件處理程序。 – thefrontender 2012-08-15 23:52:34