如何使用JavaScript检查URL中的#散列?

如何使用JavaScript检查URL中的#散列?

我有一些jQueryJavaScript代码,只有在URL中有散列(#)锚链接时才能运行。如何使用JavaScript检查这个字符?我需要一个简单的所有捕获测试来检测这样的URL:

  • example.com/page.html#锚
  • example.com/page.html#另一个锚

基本上类似于:

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

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


幕布斯7119047
浏览 303回答 3
3回答

HUX布斯

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

慕娘9325324

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   }
打开App,查看更多内容
随时随地看视频慕课网APP