问题
I have a set of Bootstrap tabs.
HTML
<ul class="nav nav-tabs" role="tablist">
<li class="active"><a href="#main" role="tab" data-toggle="tab" data-url="~/ccf/main">Main</a></li>
<li><a href="#userinfo" role="tab" data-toggle="tab" data-url="~/ccf/userinfo">User Info</a></li>
...
</ul>
<div class="tab-content">
<div class="tab-pane active" id="main"></div>
<div class="tab-pane" id="userinfo"></div>
...
</div>
JS
var url = document.location.toString();
if (url.match('#')) {
$('.nav-tabs a[href=#' + url.split('#')[1] + ']').tab('show');
}
// Change hash for page-reload
$('.nav-tabs a').on('shown', function (e) {
window.location.hash = e.target.hash;
})
// load first tab content if it is AJAX
$('#main').load($('a[data-url]:first').attr("data-url") + "&silent=1", function (data) {
$('.active a').tab('show');
});
What I want is for the what ever tab has focus to be loaded, rather than always load the first.
Update: I am getting the tab to focus. It just doesn't fire off the AJAX load
This is not the same as Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink
回答1:
The only way to go to the last tab that has the focus, is to store a reference (using cookies or local storage).
This code uses local storage to store the href value of the focused tab and later retrieve it.
$(function() {
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
localStorage.setItem('focustab', $(e.target).attr('href'));
});
var focustab = localStorage.getItem('focustab');
if (focustab) {
$('[href="' + focustab + '"]').tab('show');
}
});
来源:https://stackoverflow.com/questions/29679749/go-to-specific-tab-on-page-reload-or-hyperlink-where-tab-is-loaded-by-ajax