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

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

基本上是这样的:

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

当前回答

$('#myanchor').click(function(){
    window.location.hash = "myanchor"; //set hash
    return false; //disables browser anchor jump behavior
});
$(window).bind('hashchange', function () { //detect hash change
    var hash = window.location.hash.slice(1); //hash to string (= "myanchor")
    //do sth here, hell yeah!
});

这将解决问题;)

其他回答

下面是定期检查哈希值变化的方法,然后调用一个函数来处理哈希值。

var hash = false; 
checkHash();

function checkHash(){ 
    if(window.location.hash != hash) { 
        hash = window.location.hash; 
        processHash(hash); 
    } t=setTimeout("checkHash()",400); 
}

function processHash(hash){
    alert(hash);
}

位置哈希的简单使用:

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

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

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

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

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

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

if(hasHash(url)) {
 url = removeHash(url)
}
  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
  }

你试过这个吗?

if (url.indexOf('#') !== -1) {
    // Url contains a #
}

(url显然是你要检查的url。)