2015-04-03 78 views
0

我有一個頁面jQuery的 - 獲取URL哈希

  • 最新
  • 過期
  • 待定

當每個標籤被激活,哈希被添加到URL在三個選項卡:

http://example.com/com/#latest

我試圖在每個選項卡上添加分頁。所以我想這樣做是這樣的:

http://example.com/com/#latest?p=5

但我不知道如何通過自身獲得的哈希值。使用$(location).attr('hash')回報#latest?p=5

if($(location).attr('hash')) { 
    var tab = $(location).attr('hash'); 
}else{ 
    var tab = "#latest"; 
} 

回答

2

與代碼解析它獲得哈希

var hash = window.location.hash; 

越來越latest

var active = hash.match(/\#(\w+)/)[1]; 

越來越頁碼

var num = hash.match(/p=(\d+)/)[1]; 
+0

嗨。如果我直接訪問'http:// example.com/com /#latest',我只會得到一個'#' – Ciprian 2015-04-03 09:21:51

+0

更新我的答案 – user3896501 2015-04-03 11:04:07

5

這是一個JavaScript屬性

window.location.hash 

然後,你需要分析你的字符串。如果使用標準的查詢字符串的符號,你可以從Parse query string in JavaScript

+0

你能否解釋一下「標準查詢字符串符號」? – Ciprian 2015-04-03 09:19:14

+0

當然http://en.m.wikipedia.org/wiki/Query_string – 2015-04-03 16:11:52

0

有重要在其他答案上監督的細節:

  • 火狐返回編碼
  • 你得到的哈希值,包括初始哈希

爲了解決Firefox的問題,你需要閱讀它這樣的哈希值網址:

var hashValue = decodeURI(window.location.hash); 

這對其他瀏覽器也是安全的。

如果你想獲得無初始值已經象徵#,你只需要做到這一點:

var hashValue = decodeURI(window.location.hash).substr(1);