如何使用JavaScript检查URL中的#hash?

我有一些jQuery JavaScript代码,我只想在URL中存在散列(#)锚链接时运行。 你如何使用JavaScript检查这个角色? 我需要一个简单的全面测试来检测这些URL:

  • example.com/page.html#anchor
  • example.com/page.html#anotheranchor
  • 基本上是这样的:

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

    如果有人能指出我的方向正确,那将非常感激。


    简单:

    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/12369.html

    上一篇: How can you check for a #hash in a URL using JavaScript?

    下一篇: Why Google uses a lot of SOAP in spite of the following advantages in REST?