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

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

基本上是这样的:

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

当前回答

我注意到所有这些答案都主要检查window.location.hash,这使得编写测试变得困难。

 const hasHash = string => string.includes('#')

你也可以像这样从url中删除散列:

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

最后你可以把逻辑组合在一起:

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

其他回答

window.location.hash 

将返回哈希标识符

位置哈希的简单使用:

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

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

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

通常是点击跳转,而不是位置更改, 所以在点击之后设置timeout是一个好主意 获取更新的window.location.hash

$(".nav").click(function(){
    setTimeout(function(){
        updatedHash = location.hash
    },100);
});

或者你可以收听位置:

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

我写了一个jQuery插件 你想做什么。

这是一个简单的锚路由器。

我注意到所有这些答案都主要检查window.location.hash,这使得编写测试变得困难。

 const hasHash = string => string.includes('#')

你也可以像这样从url中删除散列:

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

最后你可以把逻辑组合在一起:

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