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

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

基本上是这样的:

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

当前回答

大多数人都知道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
   }
});

其他回答

你试过这个吗?

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

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

位置哈希的简单使用:

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

...或者有一个jquery选择器:

$('a[href^="#"]')
var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);

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

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