我有一些jQuery/JavaScript代码,我想只在URL中有一个散列(#)锚链接时运行。如何使用JavaScript检查这个字符?我需要一个简单的全方位测试,可以检测到如下url:

example.com/page.html #锚 example.com/page.html # anotheranchor

基本上是这样的:

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

当前回答

  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
  }

其他回答

下面是一个简单的函数,返回true或false(有/没有标签):

var urlToCheck = 'http://www.domain.com/#hashtag';

function hasHashtag(url) {
    return (url.indexOf("#") != -1) ? true : false;
}

// Condition
if(hasHashtag(urlToCheck)) {
    // Do something if has
}
else {
    // Do something if doesn't
}

在这种情况下返回true。

基于@jon-skeet的评论。

下面是定期检查哈希值变化的方法,然后调用一个函数来处理哈希值。

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

有时您会得到完整的查询字符串,例如“#anchorlink?”firstname =马克”

这是我获取哈希值的脚本:

var hashId = window.location.hash;
hashId = hashId.match(/#[^?&\/]*/g);

returns -> #anchorlink

写上以下内容:

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

这是一个简单的方法来测试当前页面的URL:

  function checkHash(){
      return (location.hash ? true : false);
  }