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

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

    Have you tried this?

    if (url.indexOf('#') !== -1) {
        // Url contains a #
    }
    

    (Where url is the URL you want to check, obviously.)

    0 讨论(0)
  • 2020-11-22 02:31
    window.location.hash 
    

    will return the hash identifier

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

    Most people are aware of the URL properties in document.location. That's great if you're only interested in the current page. But the question was about being able to parse anchors on a page not the page itself.

    What most people seem to miss is that those same URL properties are also available to anchor elements:

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

    If the URI is not the document's location this snippet will do what you want.

    var url = 'example.com/page.html#anchor',
        hash = url.split('#')[1];
    
    if (hash) {
        alert(hash)
    } else {
        // do something else
    }
    
    0 讨论(0)
  • 2020-11-22 02:32

    This is a simple way to test this for the current page URL:

      function checkHash(){
          return (location.hash ? true : false);
      }
    
    0 讨论(0)
  • 2020-11-22 02:33
    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; 
      }
    }
    
    0 讨论(0)
提交回复
热议问题