Javascript 使用jQuery从URL读取#散列

Javascript 使用jQuery从URL读取#散列,javascript,jquery,Javascript,Jquery,如何使用jQuery从URL返回website.com/#something(something)的哈希值?update 因为有一个内置的方法通过DOM获取哈希,所以上面的答案是不合适的 var hashTag = window.location.hash alert(hashTag); 我会变魔术的 旧答案 如果url中有多个哈希,可以执行以下操作 //var href = location.href; // get the url in real worl scenario v

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

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

   var hashTag = window.location.hash
   alert(hashTag);
我会变魔术的

旧答案 如果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);

下面是一个示例
window.location.hash
就这么简单

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

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

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

var hash = window.location.hash;

$.ajax({
    url: 'someurl.php',
    data: {hash: hash},
    success: function(){}
})
您可以使用该属性获取当前页面的哈希:

var hash = window.location.hash;
你可以用这个

h=new URL(location).hash.split`&`.find(e=>/hash_name/.test(e)).split`=`[1]

window.location.hash
its为您提供hash@Sandeep:这显然是答案,为什么不干脆把它作为答案发布呢?@DavidThomas同意!发布jus now:)@Christian u可以接受它作为答案看着@Sandeep的大写问题,你可能已经编辑/删除了自上次我查看以来的评论,所以我可以问一下:你想用哈希做什么?显示/隐藏某些内容,将其提交到服务器(Ajax等),与另一个变量或其他完全不同的内容连接?DOM已经为您提供了一个预定义的变量位置。哈希然后使用这种方法是浪费我没有否决投票,但这比需要的复杂得多。@DavidThomas我同意您的看法。更新了答案。这个问题的投票很奇怪。正确答案得到两张反对票,而复杂的答案后来改为复制正确答案得到两张赞成票。我知道如何进行ajax调用,但这是唯一的方法?是的,这是从浏览器访问服务器端语言的唯一方法。为什么这样不好?