问题
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;
}
回答1:
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
回答2:
Check this jQuery plugin:
- http://benalman.com/projects/jquery-hashchange-plugin/
- http://benalman.com/code/projects/jquery-hashchange/docs/files/jquery-ba-hashchange-js.html
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();
来源:https://stackoverflow.com/questions/12469350/how-can-i-get-hash-code-from-url-when-i-write-url-and-press-enter