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

前端 未结 19 2758
说谎
说谎 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:45

    Usually clicks go first than location changes, so after a click is a good idea to setTimeOut to get updated window.location.hash

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

    or you can listen location with:

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

    I wrote a jQuery plugin that does something like what you want to do.

    It's a simple anchor router.

    0 讨论(0)
提交回复
热议问题