How can you check for a #hash in a URL using JavaScript?

前端 未结 19 2796
说谎
说谎 2020-11-22 02:10

I have some jQuery/JavaScript code that I want to run only when there is a hash (#) anchor link in a URL. How can you check for this character using JavaScript?

相关标签:
19条回答
  • 2020-11-22 02:39

    Throwing this in here as a method for abstracting location properties from arbitrary URI-like strings. Although window.location instanceof Location is true, any attempt to invoke Location will tell you that it's an illegal constructor. You can still get to things like hash, query, protocol etc by setting your string as the href property of a DOM anchor element, which will then share all the address properties with window.location.

    Simplest way of doing this is:

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

    For convenience, I wrote a little library that utilises this to replace the native Location constructor with one that will take strings and produce window.location-like objects: Location.js

    0 讨论(0)
  • 2020-11-22 02:39

    sometimes you get the full query string such as "#anchorlink?firstname=mark"

    this is my script to get the hash value:

    var hashId = window.location.hash;
    hashId = hashId.match(/#[^?&\/]*/g);
    
    returns -> #anchorlink
    
    0 讨论(0)
  • 2020-11-22 02:40
    $('#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!
    });
    

    This will solve the problem ;)

    0 讨论(0)
  • 2020-11-22 02:41
    var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);
    
    0 讨论(0)
  • 2020-11-22 02:41

    You can parse urls using modern JS:

    var my_url = new URL('http://www.google.sk/foo?boo=123#baz');
    
    my_url.hash; // outputs "#baz"
    my_url.pathname; // outputs "/moo"
    ​my_url.protocol; // "http:"
    ​my_url.search; // outputs "?doo=123"
    

    urls with no hash will return empty string.

    0 讨论(0)
  • 2020-11-22 02:44

    ...or there's a jquery selector:

    $('a[href^="#"]')
    
    0 讨论(0)
提交回复
热议问题