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

Phi*_*ton 754 javascript anchor jquery fragment-identifier

我有一些jQuery JavaScript代码,我想只在URL中有一个哈希(#)锚链接时运行.如何使用JavaScript检查此角色?我需要一个简单的catch-all测试来检测这样的URL:

  • example.com/page.html#anchor
  • example.com/page.html#anotheranchor

基本上是这样的:

if (thereIsAHashInTheUrl) {        
    do this;
} else {
    do this;
}
Run Code Online (Sandbox Code Playgroud)

如果有人能指出我正确的方向,那将非常感激.

Gar*_*eth 1355

简单:

if(window.location.hash) {
  // Fragment exists
} else {
  // Fragment doesn't exist
}
Run Code Online (Sandbox Code Playgroud)

  • 此外,<a>元素也可以使用.hash和.query等位置属性 (63认同)
  • 附加:.location对象仅在当前窗口的URL上可用,您不能对任意URL(例如存储在字符串变量中的URL)执行此操作 (41认同)
  • `.search`可用于`<a>`,而不是`.query`.示例jQuery:`$("<a/>").attr({"href":"http://www.somewhere.com/a/b/c.html?qs=1#fragmenttest"})[0 ]`.`.hash =>"#fraragtest"`和`.search` =`?qs = 1`.从那里,点击[查询字符串提取问题](http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript)获取字符串以外的内容. (18认同)
  • 请注意,如果 url 以“#”结尾,则“window.location.hash”为空。如果您要查找哈希值,则可以,但如果您要检查当前 URL 是否包含#,则不行。 (5认同)
  • @Gareth是的,你是对的.刚刚意识到我发布的链接是针对`hashchange`事件而不是`window.location.hash`.虽然IE <8不支持后者. (2认同)

Mar*_*ton 313

  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
  }
Run Code Online (Sandbox Code Playgroud)


Jos*_*eal 52

把以下内容:

<script type="text/javascript">
    if (location.href.indexOf("#") != -1) {
        // Your code in here accessing the string like this
        // location.href.substr(location.href.indexOf("#"))
    }
</script>
Run Code Online (Sandbox Code Playgroud)


Mar*_*elm 32

如果URI不是文档的位置,则此代码段将执行您想要的操作.

var url = 'example.com/page.html#anchor',
    hash = url.split('#')[1];

if (hash) {
    alert(hash)
} else {
    // do something else
}
Run Code Online (Sandbox Code Playgroud)

  • @Dunc:好的JS数组基本上都是对象.通过索引访问它们就像访问Object属性一样:`obj ['0']`.在JS中这是真的:`arr [0] === arr ['0']`因此,如果索引/键不存在,则返回的值是未定义的而不是超出范围.http://jsfiddle.net/web5me/Mw376/ (2认同)

Jon*_*eet 19

你试过这个吗?

if (url.indexOf('#') !== -1) {
    // Url contains a #
}
Run Code Online (Sandbox Code Playgroud)

(url显然,您要检查的URL 在哪里.)


小智 15

$('#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!
});
Run Code Online (Sandbox Code Playgroud)

这将解决问题;)


小智 12

window.location.hash 
Run Code Online (Sandbox Code Playgroud)

将返回哈希标识符


Bar*_*fen 10

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

$('a[href^="#"]')
Run Code Online (Sandbox Code Playgroud)


Fus*_*ion 7

您可以使用现代 JS解析 url :

\n
var my_url = new URL(\'http://www.google.sk/foo?boo=123#baz\');\n\nmy_url.hash; // outputs "#baz"\nmy_url.pathname; // outputs "/moo"\n\xe2\x80\x8bmy_url.protocol; // "http:"\n\xe2\x80\x8bmy_url.search; // outputs "?doo=123"\n
Run Code Online (Sandbox Code Playgroud)\n

没有哈希值的 url 将返回空字符串。

\n


Emm*_*uel 6

以下是您可以定期检查哈希值的变化,然后调用函数来处理哈希值.

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 这仅仅是6 + 7中的nesses.其他浏览器包含了onhashchange事件 (10认同)
  • 这根本不是推荐的代码:它至少应该是:`setTimeout(checkHash,400)`.此外,现代浏览器具有`hashchange`事件,因此您可以执行`window.addEventListener('hashchange',function(){...})`.最后,泄漏全局`hash`变量是另一种非推荐的做法,即使是例证. (4认同)

小智 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; 
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 那不应该是“hash.length”而不是“hash.length()”吗?:) (3认同)

小智 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
   }
});
Run Code Online (Sandbox Code Playgroud)