2015-04-03 77 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);