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

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

    Here's what you can do to periodically check for a change of hash, and then call a function to process the hash value.

    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);
    }
    
    0 讨论(0)
  • 2020-11-22 02:24
      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
      }
    
    0 讨论(0)
  • 2020-11-22 02:24

    Here is a simple function that returns true or false (has / doesn't have a hashtag):

    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
    }
    

    Returns true in this case.

    Based on @jon-skeet's comment.

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

    Partridge and Gareths comments above are great. They deserve a separate answer. Apparently, hash and search properties are available on any html Link object:

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

    Or

    <a href="bar.html?foo" onclick="alert(this.search)">SAY FOO</a>
    

    Should you need this on a regular string variable and happen to have jQuery around, this should work:

    var mylink = "foo.html?bar#quz";
    
    if ($('<a href="'+mylink+'">').get(0).search=='bar')) {
        // do stuff
    }
    

    (but its maybe a bit overdone .. )

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

    Simple:

    if(window.location.hash) {
      // Fragment exists
    } else {
      // Fragment doesn't exist
    }
    
    0 讨论(0)
  • 2020-11-22 02:27

    Put the following:

    <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>
    
    0 讨论(0)
提交回复
热议问题