如何使用JavaScript检查URL中的#哈希标识?

914

我有一些jQuery/JavaScript代码,我希望只在URL中存在散列符号(#)时运行它。如何使用JavaScript检查此字符?我需要一个简单的测试,可以检测到这样的URL:

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

基本上是这样:

if (thereIsAHashInTheUrl) {
    do this;
} else {
    do this;
}
20个回答

1624

使用位置哈希值的简单方法:

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

51
额外提示:.location对象仅适用于当前窗口的URL,您无法对任意URL执行此操作(例如存储在字符串变量中的URL)。 - Gareth
74
同时,像 .hash 和 .query 这样的位置属性也可以在 <a> 元素上使用。 - Gareth
22
.search 方法可用于 <a> 元素而非 .query。示例 jQuery 代码如下:$("<a/>").attr({ "href": "http://www.somewhere.com/a/b/c.html?qs=1#fragmenttest" })[0].hash => "#fragmenttest".search = ?qs=1。接下来,请查看 querystring extraction question 中的问题以获取除字符串以外的其他内容。 - patridge
5
请注意,如果URL以“#”结尾,则 window.location.hash为空。 如果您正在寻找哈希,则没有问题,但是如果您想检查当前URL是否包含“#”,则不行。 - fela

389
  if(window.location.hash) {
      var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
      alert (hash);
      // hash found
  } else {
      // No hash found
  }

58

请放置以下内容:

<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>

45
如果URI不是文档的位置,此片段将执行您所需的操作。
var url = 'example.com/page.html#anchor',
    hash = url.split('#')[1];

if (hash) {
    alert(hash)
} else {
    // do something else
}

30

你试过这个吗?

if (url.indexOf('#') !== -1) {
    // Url contains a #
}

(其中url是你想要检查的URL,显然。)


18
$('#myanchor').click(function(){
    window.location.hash = "myanchor"; //set hash
    return false; //disables browser anchor jump behavior
});
$(window).bind('hashchange', function () { //detect hash change
    var hash = window.location.hash.slice(1); //hash to string (= "myanchor")
    //do sth here, hell yeah!
});

这会解决问题的;)


17
window.location.hash 

将返回哈希标识符


10

...或者有一个jQuery选择器:

$('a[href^="#"]')

7
您可以使用现代JS解析URL:
var my_url = new URL('http://www.google.sk/foo?boo=123#baz');

my_url.hash; // outputs "#baz"
my_url.pathname; // outputs "/moo"
​my_url.protocol; // "http:"
​my_url.search; // outputs "?doo=123"

没有哈希的URL将返回空字符串。

6

以下是您可以定期检查哈希值更改并调用函数处理哈希值的方法。

var hash = false; 
checkHash();

function checkHash(){ 
    if(window.location.hash != hash) { 
        hash = window.location.hash; 
        processHash(hash); 
    } t=setTimeout("checkHash()",400); 
}

function processHash(hash){
    alert(hash);
}

12
只有在IE 6和7中才需要这样做。其他所有浏览器都包含了onhashchange事件。 - Tokimon

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