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

我有一些jQuery / JavaScript代码,仅当#URL中有哈希()锚链接时才要运行如何使用JavaScript检查此字符?我需要一个简单的包罗万象的测试,该测试可以检测如下URL:

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

基本上是这样的:

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

如果有人能指出我正确的方向,那将不胜感激。

樱Mandy2020/03/11 10:41:36

This is a simple way to test this for the current page URL:

  function checkHash(){
      return (location.hash ? true : false);
  }
Sam蛋蛋Itachi2020/03/11 10:41:36

sometimes you get the full query string such as "#anchorlink?firstname=mark"

this is my script to get the hash value:

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

returns -> #anchorlink
GO村村2020/03/11 10:41:36
var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);
逆天蛋蛋达蒙2020/03/11 10:41:36
function getHash() {
  if (window.location.hash) {
    var hash = window.location.hash.substring(1);

    if (hash.length === 0) { 
      return false;
    } else { 
      return hash; 
    }
  } else { 
    return false; 
  }
}
LEY蛋蛋2020/03/11 10:41:36
window.location.hash 

will return the hash identifier

达蒙阿飞斯丁2020/03/11 10:41:36

输入以下内容:

<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>
西里Mandy2020/03/11 10:41:36
  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
  }