如何使用 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;
}

原文由 Philip Morton 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 777
2 个回答

位置哈希 的简单使用:

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

原文由 Gareth 发布,翻译遵循 CC BY-SA 4.0 许可协议

  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
  }

原文由 Mark Notton 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题