【问题标题】:How can you check for a #hash in a URL using JavaScript?如何使用 JavaScript 检查 URL 中的#hash?
【发布时间】:2010-09-22 20:19:33
【问题描述】:

我有一些 jQuery/JavaScript 代码,我只想在 URL 中有哈希 (#) 锚链接时运行这些代码。如何使用 JavaScript 检查这个字符?我需要一个简单的包罗万象的测试来检测这样的 URL:

  • example.com/page.html#anchor
  • example.com/page.html#anotheranchor

基本上是这样的:

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

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

【问题讨论】:

    标签: javascript jquery anchor fragment-identifier


    【解决方案1】:

    location hash的简单使用:

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

    【讨论】:

    • 附加:.location 对象仅在当前窗口的 URL 上可用,您不能对任意 URL 执行此操作(例如存储在字符串变量中的 URL)
    • 此外,.hash 和 .query 等位置属性也可用于 元素
    • .search<a> 上可用,而不是.query。示例 jQuery:$("<a/>").attr({ "href": "http://www.somewhere.com/a/b/c.html?qs=1#fragmenttest" })[0].hash => "#fragmenttest".search = ?qs=1。从那里,点击querystring extraction question 以获取字符串以外的其他内容。
    • 请注意,如果 url 以 '#' 结尾,window.location.hash 为空。如果您正在查找哈希,则可以,但如果您正在检查当前 URL 是否包含 #,则不行。
    【解决方案2】:
      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
      }
    

    【讨论】:

      【解决方案3】:

      输入以下内容:

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

      【讨论】:

        【解决方案4】:

        如果 URI 不是文档的位置,这个 sn-p 会做你想做的事。

        var url = 'example.com/page.html#anchor',
            hash = url.split('#')[1];
        
        if (hash) {
            alert(hash)
        } else {
            // do something else
        }
        

        【讨论】:

          【解决方案5】:

          你试过了吗?

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

          url 显然是您要检查的 URL。)

          【讨论】:

            【解决方案6】:
            $('#myanchor').click(function(){
                window.location.hash = "myanchor"; //set hash
                return false; //disables browser anchor jump behavior
            });
            $(window).bind('hashchange', function () { //detect hash change
                var hash = window.location.hash.slice(1); //hash to string (= "myanchor")
                //do sth here, hell yeah!
            });
            

            这将解决问题;)

            【讨论】:

              【解决方案7】:
              window.location.hash 
              

              将返回哈希标识符

              【讨论】:

                【解决方案8】:

                ...或者有一个 jquery 选择器:

                $('a[href^="#"]')
                

                【讨论】:

                  【解决方案9】:

                  您可以执行以下操作来定期检查哈希值的变化,然后调用函数来处理哈希值。

                  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);
                  }
                  

                  【讨论】:

                  • 这只是 ie 6 + 7 中的必要条件。所有其他浏览器都包含了 onhashchange 事件
                  【解决方案10】:

                  大多数人都知道 document.location 中的 URL 属性。如果您只对当前页面感兴趣,那就太好了。但问题在于能够解析页面上的锚点而不是页面本身。

                  大多数人似乎错过的是,这些相同的 URL 属性也可用于锚元素:

                  // 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
                     }
                  });
                  

                  【讨论】:

                    【解决方案11】:
                    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; 
                      }
                    }
                    

                    【讨论】:

                      【解决方案12】:
                      var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);
                      

                      【讨论】:

                        【解决方案13】:

                        上面的 Partridge 和 Gareths cmets 很棒。他们应该得到一个单独的答案。 显然,任何 html Link 对象都可以使用 hash 和 search 属性:

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

                        或者

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

                        如果您需要在常规字符串变量上使用它并且碰巧有 jQuery, 这应该工作:

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

                        (但它可能有点过头了..)

                        【讨论】:

                          【解决方案14】:

                          在此处将其作为一种从任意类似 URI 的字符串中抽象位置属性的方法。尽管window.location instanceof Location 为真,但任何调用Location 的尝试都会告诉您这是一个非法构造函数。您仍然可以通过将您的字符串设置为 DOM 锚元素的href 属性来访问hashqueryprotocol 等内容,然后它将与window.location 共享所有地址属性。

                          最简单的方法是:

                          var a = document.createElement('a');
                          a.href = string;
                          
                          string.hash;
                          

                          为方便起见,我编写了一个小库,利用它来替换原生的 Location 构造函数,用一个接受字符串并生成类似 window.location 的对象:Location.js

                          【讨论】:

                            【解决方案15】:

                            通常点击先于位置更改, 所以点击后设置TimeOut是个好主意 获取更新的 window.location.hash

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

                            或者您可以使用以下方式收听位置:

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

                            我写了一个jQuery plugin,它做了类似的事情 你想做什么。

                            这是一个简单的锚路由器。

                            【讨论】:

                              【解决方案16】:

                              这是一个简单的函数,它返回truefalse(有/没有标签):

                              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
                              }
                              

                              在这种情况下返回true

                              基于@jon-skeet 的评论。

                              【讨论】:

                                【解决方案17】:

                                您可以使用modern JS 解析网址:

                                var my_url = new URL('http://www.google.sk/foo?boo=123#baz');
                                
                                my_url.hash; // outputs "#baz"
                                my_url.pathname; // outputs "/moo"
                                ​my_url.protocol; // "http:"
                                ​my_url.search; // outputs "?doo=123"
                                

                                没有哈希的网址将返回空字符串。

                                【讨论】:

                                  【解决方案18】:

                                  这是测试当前页面 URL 的简单方法:

                                    function checkHash(){
                                        return (location.hash ? true : false);
                                    }
                                  

                                  【讨论】:

                                    【解决方案19】:

                                    我注意到所有这些答案大多检查 window.location.hash 并且难以编写测试。

                                     const hasHash = string => string.includes('#')
                                    

                                    您也可以像这样从 url 中删除哈希:

                                    const removeHash = string => {
                                     const [url] = string.split('#')
                                     return url
                                    }
                                    

                                    最后你可以将逻辑组合在一起:

                                    if(hasHash(url)) {
                                     url = removeHash(url)
                                    }
                                    

                                    【讨论】:

                                      【解决方案20】:

                                      有时您会得到完整的查询字符串,例如“#anchorlink?firstname=mark”

                                      这是我获取哈希值的脚本:

                                      var hashId = window.location.hash;
                                      hashId = hashId.match(/#[^?&\/]*/g);
                                      
                                      returns -> #anchorlink
                                      

                                      【讨论】:

                                      • 不可能,因为哈希附加在查询字符串之后,并且永远不会发送到服务器。唯一一次哈希出现在查询字符串之前是当你手动修改 url 时。
                                      • 是的,但有时人们会以这种格式发送网址。这只是为了让您只能获得哈希值而忽略其他值。 :)
                                      猜你喜欢
                                      • 2023-03-10
                                      • 2014-03-17
                                      • 2022-11-19
                                      • 1970-01-01
                                      • 2015-05-14
                                      • 1970-01-01
                                      • 2018-12-10
                                      • 2012-04-05
                                      • 1970-01-01
                                      相关资源
                                      最近更新 更多