首页 文章

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

提问于
浏览
695

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

  • example.com/page.html#anchor

  • example.com/page.html#anotheranchor

基本上是这样的:

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

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

18 回答

  • 3

    简单:

    if(window.location.hash) {
      // Fragment exists
    } else {
      // Fragment doesn't exist
    }
    
  • 3
    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
      }
    
  • -2

    把以下内容:

    <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>
    
  • 18

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

    var url = 'example.com/page.html#anchor',
        hash = url.split('#')[1];
    
    if (hash) {
        alert(hash)
    } else {
        // do something else
    }
    
  • 12

    你试过这个吗?

    if (url.indexOf("#") != -1)
    {
    }
    

    (显然, url 是您要检查的URL . )

  • 0
    $('#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!
    });
    

    这将解决问题;)

  • 283
    window.location.hash
    

    将返回哈希标识符

  • 5

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

    $('a[href^="#"]')
    
  • 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);
    }
    
  • 1242

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

    上面的Partridge和Gareths评论很棒 . 他们应该得到一个单独的答案 . 显然,任何html Link对象都可以使用哈希和搜索属性:

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

    (但它可能有点过头了..)

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

    将此作为一种从任意类似URI的字符串中抽象位置属性的方法 . 虽然 window.location instanceof Location 为true,但任何调用 Location 的尝试都会告诉您它是非法的构造函数 . 您仍然可以通过将字符串设置为DOM锚元素的 href 属性来获取 hashqueryprotocol 等内容,然后使用 window.location 共享所有地址属性 .

    最简单的方法是:

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

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

  • 0

    通常点击首先比位置更改,所以点击后最好是setTimeOut来获取更新的window.location.hash

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

    或者你可以听取位置:

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

    我写了一个jQuery plugin,做了类似你想做的事情 .

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

  • 15

    这是一个返回 truefalse 的简单函数(有/没有#标签):

    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的评论 .

  • 46

    这是为当前页面URL测试此方法的简单方法:

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

    有时你得到完整的查询字符串,如“#anchorlink?firstname = mark”

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

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

相关问题