9

如何website.com/#something使用 jQuery 从 URL 返回(某物)的哈希值?

4

4 回答 4

17

window.location.hash 就这么简单。

不要使用所有那些消耗 CPU 和影响性能的方法。

如果 DOM 提供了一些预定义的东西,请先使用它。

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

var hash = window.location.hash;

$.ajax({
    url: 'someurl.php',
    data: {hash: hash},
    success: function(){}
})
于 2013-04-01T10:12:07.373 回答
4

您可以使用location.hash属性来获取当前页面的哈希:

var hash = window.location.hash;
于 2013-04-01T10:12:19.493 回答
1

更新

因为有一个内置的方法可以通过 DOM 获取哈希,所以上面的答案是不合适的

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

会变魔术。

旧答案

如果您的网址中有多个哈希值,您可以执行以下操作

//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);

这是一个例子Live Fiddle

于 2013-04-01T10:08:01.293 回答
-1

你可以用这个

h=new URL(location).hash.split`&`.find(e=>/hash_name/.test(e)).split`=`[1]
于 2020-07-26T06:14:35.747 回答