如何使用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个回答

5

大多数人都知道document.location中的URL属性。如果你只对当前页面感兴趣,那很好。但问题在于如何解析页面上的锚点而不是页面本身。

大多数人似乎忽略了相同的URL属性也适用于锚元素:

// To process anchors on click    
jQuery('a').click(function () {
   if (this.hash) {
      // Clicked anchor has a hash
   } else {
      // Clicked anchor does not have a hash
   }
});

// To process anchors without waiting for an event
jQuery('a').each(function () {
   if (this.hash) {
      // Current anchor has a hash
   } else {
      // Current anchor does not have a hash
   }
});

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

4
var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);

3

Partridge和Gareth上面的评论很好。他们值得一个单独的回答。 显然,散列和搜索属性可以在任何HTML链接对象上使用:

<a id="test" href="foo.html?bar#quz">test</a>
<script type="text/javascript">
   alert(document.getElementById('test').search); //bar
   alert(document.getElementById('test').hash); //quz
</script>

或者

<a href="bar.html?foo" onclick="alert(this.search)">SAY FOO</a>

如果您需要在常规字符串变量上进行此操作并恰好有jQuery,可以使用以下方法:

应该这样做:

var mylink = "foo.html?bar#quz";

if ($('<a href="'+mylink+'">').get(0).search=='bar')) {
    // do stuff
}

(但可能有点过了……)

3

在这里介绍一种将位置属性从任意类似URI的字符串中抽象出来的方法。虽然window.location instanceof Location为真,但任何尝试调用Location将告诉你它是一个非法的构造函数。您仍然可以通过将字符串设置为DOM锚点元素的 href 属性来访问 hash query protocol 等内容,然后该元素将与 window.location 共享所有地址属性。

最简单的方法是:

var a = document.createElement('a');
a.href = string;

string.hash;

为方便起见,我编写了一个小型库,利用这个库可以替换原生的Location构造函数,该构造函数接受字符串并生成类似于window.location的对象:Location.js


1
通常点击事件会先于位置变化发生, 因此在点击后设置 setTimeOut 以获取更新的 window.location.hash 是个好主意。
$(".nav").click(function(){
    setTimeout(function(){
        updatedHash = location.hash
    },100);
});

或者您可以使用以下方式获取位置信息:

window.onhashchange = function(evt){
   updatedHash = "#" + evt.newURL.split("#")[1]
};

我写了一个jQuery插件,可以做你想要的事情。

它是一个简单的锚点路由器。


1
这是一种简单的测试当前页面URL的方法:
  function checkHash(){
      return (location.hash ? true : false);
  }

1
这是一个简单的函数,返回truefalse(是否有hashtag):
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的评论。

1
我注意到,所有这些答案大多检查window.location.hash,并使编写测试变得困难。
 const hasHash = string => string.includes('#')

您也可以这样从url中删除哈希:

const removeHash = string => {
 const [url] = string.split('#')
 return url
}

最后,您可以将这些逻辑组合在一起:

if(hasHash(url)) {
 url = removeHash(url)
}

-2

有时候你会得到完整的查询字符串,比如"#anchorlink?firstname=mark"

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

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

returns -> #anchorlink

8
由于哈希标识符被附加在查询字符串之后并且从未发送到服务器,所以无法实现。唯一出现哈希标识符位于查询字符串之前的情况是手动修改URL时。 - user1537415
1
是的,但有时人们会以这种格式发送URL。 这只是让您仅获取哈希值并忽略其他内容。 :) - markg

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