使用jQuery从URL读取#hash

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

window.location.hash这么简单。

不要使用所有消耗CPU和效果性能的方法。

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

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

 var hash = window.location.hash; $.ajax({ url: 'someurl.php', data: {hash: hash}, success: function(){} }) 

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

 var hash = window.location.hash; 

更新

由于有一个内置的方法通过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); 

这是Live Fiddle的一个例子

您可以使用javascript获取哈希值并将其传递给jquery。

例如:

 var url = window.location.href; var hash = url.substring(url.indexOf('#')); $(hash).trigger('click');