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

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? I need a simple catch-all test that would detect URLs like these:

  • example.com/page.html#anchor
  • example.com/page.html#anotheranchor
  • Basically something along the lines of:

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

    If anyone could point me in the right direction, that would be much appreciated.


    简单:

    if(window.location.hash) {
      // Fragment exists
    } else {
      // Fragment doesn't exist
    }
    

      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
      }
    

    提出以下建议:

    <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>
    
    链接地址: http://www.djcxy.com/p/12370.html

    上一篇: 我应该在HTML标记中放置<script>标记?

    下一篇: 如何使用JavaScript检查URL中的#hash?