【问题标题】:How can i get hash code from url when i write url and press enter?当我编写 url 并按 Enter 时,如何从 url 获取哈希码?
【发布时间】:2012-09-10 06:21:33
【问题描述】:

我有这个网址:example.com/index.html#tab-1

我按照 url example.com/index.html#tab-1 写入浏览器并按 Enter - 页面将无法加载。

我想获取参数tab1并加载id为tab1的内容。

我的代码:

我称之为函数:

//to load

showTabContent(gethash);


showTabContent: function(id)
        {
            if(id != null)
            {
                var tabid = id.split("-");
                $("#tab"+tabid[1]).show();
            }
        },

gethash: function()
        {
            var hash = window.location.hash;
            if($.trim(hash) != "") return hash;
            else return null;
        }

【问题讨论】:

    标签: jquery url hashtag


    【解决方案1】:

    您可以使用此函数将 URL 解析为对象:http://james.padolsey.com/javascript/parsing-urls-with-the-dom/。取回对象后,您可以使用对象的属性来获取您想要的 URL 部分。

    这篇文章中提供了类似的答案:String URL to json object

    【讨论】:

      【解决方案2】:

      检查这个 jQuery 插件:

      JS 文件:https://raw.github.com/cowboy/jquery-hashchange/master/jquery.ba-hashchange.min.js

      您的代码的解决方案:

      HTML:

      <a href="#tab-1">Tab1</a>
      <div id="tab1"></div>
      

      JS:

      obj = {
          checkHash: function(){
              $(window).hashchange( function(){
                  var hash = location.hash;
                  obj.showTabContent(hash);
              })
          },
          showTabContent: function(id)
          {
              var tabid = id.split("-");
              $("#tab"+tabid[1]).show();
          } 
      };
      
      //init
      obj.checkHash();
      

      【讨论】:

        猜你喜欢
        • 2015-10-17
        • 2012-10-31
        • 1970-01-01
        • 1970-01-01
        • 2011-04-20
        • 1970-01-01
        • 2011-12-11
        • 1970-01-01
        • 2011-02-09
        相关资源
        最近更新 更多