如何读取当前页面 URL 的 #hash(或片段标识符)?

10
如果我在 https://www.website.com/#something 上,我该如何从URL中返回哈希值 "something"

4
window.location.hash 返回当前 URL 中的哈希值。 - Sandeep
1
@Sandeep:那显然就是答案,为什么不直接发布成回答呢? - David Thomas
刚刚发布了 :) @Christian 您可以将其接受为答案。 - Sandeep
传值给PHP???进行一个ajax调用并将哈希值发送到PHP。 - Sandeep
1
看到@Sandeep的大写问题,你可能已经编辑/删除了评论,所以我可以问一下:你想用哈希做什么?显示/隐藏某些内容,将其提交到服务器(Ajax等),与另一个变量连接或其他完全不同的事情? - David Thomas
显示剩余3条评论
4个回答

17

window.location.hash 就是这么简单。

不要使用那些会消耗CPU并影响性能的方法。

如果DOM提供了预定义的内容,请首先使用它。

要将值传递到PHP,请执行ajax调用到php。

var hash = window.location.hash;

$.ajax({
    url: 'someurl.php',
    data: {hash: hash},
    success: function(){}
})

我知道如何进行ajax调用,但这是唯一的方法吗? - user1661548
据我所知,这是从浏览器访问服务器端语言的唯一方式。 - Sandeep

4
你可以使用 location.hash 属性获取当前页的哈希值:
var hash = window.location.hash;

1

更新

由于存在通过DOM获取哈希的内置方法,因此上述答案不合适。

   var hashTag = window.location.hash
   alert(hashTag);

如果您在URL中有多个哈希值,可以按照以下方式进行操作。

旧的回答

如果您在URL中有多个哈希值,可以按照以下方式进行操作。

//var href = location.href; // get the url in real worl scenario
var href = "www.bla.com#myhashtag"; // example url
var split = href.split("#"); // split the string; usually there'll be only one # in an url so there'll be only two parts after the splitting
var afterSplit = "Error parsing url";
if(split[1] != null){
    afterSplit = split[1];
}
// If everything went well shows split[1], if not then de default error message is shown
alert(afterSplit);

这是一个例子:现场小提琴

DOM已经提供了一个预定义变量location.hash,因此使用这种方法是浪费的。 - Sandeep
2
我没有点踩,但这比必要的复杂多了。 - David Thomas
@DavidThomas 我同意你的观点。已更新答案。 - Jay Mayu
1
这个问题的投票很奇怪。正确答案得到两个踩,而复杂的答案后来改成了正确答案并得到两个赞。 - gilly3

-1
你可以使用这个。
h=new URL(location).hash.split`&`.find(e=>/hash_name/.test(e)).split`=`[1]

为什么这样不好? - DerpyCoder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接