How can i get hash code from url when i write url

2019-07-07 06:14发布

I have this url: example.com/index.html#tab-1

I write into browser following url example.com/index.html#tab-1 and press enter - page will not load.

I want to get the parameter tab1 and load content with id tab1.

My code:

I call this functions:

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

2条回答
冷血范
2楼-- · 2019-07-07 07:11

You can use this function to parse the URL into an object: http://james.padolsey.com/javascript/parsing-urls-with-the-dom/. After you get the object back, you can use the properties of the object to get the parts of the URL you want.

A similar answer was provided in this post: String URL to json object

查看更多
放荡不羁爱自由
3楼-- · 2019-07-07 07:13

Check this jQuery plugin:

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

The solution for your code:

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();
查看更多
登录 后发表回答