问题
Looking to allow user to nav through multiple Tabs on a page, but when hitting the back button, return to their previous page (not have to navigate back through their Tab history). It feels like one or the other with the method I'm using (either I change the URL and deal with the history, or I don't change the URL and don't deal with the history). I have looked into HTML History API, it doesn't seem to speak directly to this, nor do many of the posts I've found. I'd like my Tabs to be link-able to, but not act as separate pages to the browser (am I nuts?). Thank you very much.
JavaScript
//add tab id to url
var hash = window.location.hash;
hash && $('ul.nav a[href="' + hash + '"]').tab('show');
$('.nav-tabs a').click(function (e) {
$(this).tab('show');
window.location.hash = this.hash;
});
HTML
<div class="tabbable">
<ul class="nav nav-tabs">
<li><a href="#tab1" data-toggle="tab">My First Tab</a></li>
<li><a href="#tab2" data-toggle="tab">My Second Tab</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="tab1">
<div id="ContentPaneTab1" runat="server"></div>
</div>
<div class="tab-pane" id="tab2">
<div id="ContentPaneTab2" runat="server"></div>
</div>
</div>
</div>
回答1:
If you are using jQuery ui to create the tabs, you can use the following to initiate the tabs:
$( "#tabs" ).tabs({
activate: function(event, ui) {
window.location.replace('#' + $(ui.newPanel).attr('id'));
}
});
This will add the newly clicked #
into the browser urkl without adding it to the history
Example
回答2:
With help from @Pete, I was able to come up with a sufficient answer using my current set up (ie not switching to jQuery UI).
This first aspect of the js takes care of the initial issue of creating history when a tab is clicked (thanks to Pete's suggestion of using '.replace' versus '.hash =')
$('.nav-tabs a').click(function (e) {
var myTab = $(this).tab();
window.location.replace($(myTab).attr('href'));
//go to top of page instead of hashtag location
window.scrollTo(0, 0);
});
Then, in case the user enters the page with a URL already containing the hashtag in it, open the respective tab.
// if window.location.hash = true, than open the tab where tab x.href == hash
if(window.location.hash) {
var hash = window.location.hash;
$('ul.nav a[href="' + hash + '"]').tab('show');
//go to top of page instead of hashtag location
window.onload = function(){
window.scrollTo(0, 0);
}
}
[using bootstrap 2 tab js]
来源:https://stackoverflow.com/questions/24613027/using-jquery-hash-to-alter-url-without-bookmarking