如何用JavaScript检查URL中的#hash?

我有一些jQuery/JavaScript代码,我想只在URL中出现哈希(#)锚链接时运行。如何用JavaScript来检查这个字符?我需要一个简单的全能测试,可以检测出这样的URL。

  • example.com/page.html#anchor
  • example.com/page.html#anotheranchor

基本上类似这样的测试。

if (thereIsAHashInTheUrl) {        
    do this;
} else {
    do this;
}

如果有人能给我指出正确的方向,那将是非常感激的。

解决办法

简单。

if(window.location.hash) {
  // Fragment exists
} else {
  // Fragment doesn't exist
}
评论(11)

放置以下内容。

<script type="text/javascript">
    if (location.href.indexOf("#") != -1) {
        // Your code in here accessing the string like this
        // location.href.substr(location.href.indexOf("#"))
    }
</script>
评论(1)

你试过这个吗?

``javascript if (url.indexOf('#') !==-1) { // Url包含一个# }



(其中`url`是你想检查的URL,显然。)
评论(0)