jQuery Bootstrap 3:在页面刷新时保留选定的选项卡
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18999501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bootstrap 3: Keep selected tab on page refresh
提问by Code Lover
I am trying to keep selected tab activeon refresh with Bootstrap 3. Tried and checked with some question already been asked here but none of work for me. Don't know where I am wrong. Here is my code
我正在尝试使用Bootstrap 3在刷新时保持所选选项卡处于活动状态。尝试并检查了一些已经在这里问过的问题,但对我来说没有用。不知道我错在哪里。这是我的代码
HTML
HTML
<!-- tabs link -->
<ul class="nav nav-tabs" id="rowTab">
<li class="active"><a href="#personal-info" data-toggle="tab">Personal Information</a></li>
<li><a href="#Employment-info" data-toggle="tab">Employment Information</a></li>
<li><a href="#career-path" data-toggle="tab">Career Path</a></li>
<li><a href="#warnings" data-toggle="tab">Warning</a></li>
</ul>
<!-- end: tabs link -->
<div class="tab-content">
<div class="tab-pane active" id="personal-info">
tab data here...
</div>
<div class="tab-pane" id="Employment-info">
tab data here...
</div>
<div class="tab-pane" id="career-path">
tab data here...
</div>
<div class="tab-pane" id="warnings">
tab data here...
</div>
</div>
Javascript:
Javascript:
// tab
$('#rowTab a:first').tab('show');
//for bootstrap 3 use 'shown.bs.tab' instead of 'shown' in the next line
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
//save the latest tab; use cookies if you like 'em better:
localStorage.setItem('selectedTab', $(e.target).attr('id'));
});
//go to the latest tab, if it exists:
var selectedTab = localStorage.getItem('selectedTab');
if (selectedTab) {
$('#'+selectedTab).tab('show');
}
回答by koppor
I prefer storing the selected tab in the hashvalue of the window. This also enables sending links to colleagues, who than see "the same" page. The trick is to change the hash of the location when another tab is selected. If you already use # in your page, possibly the hash tag has to be split. In my app, I use ":" as hash value separator.
我更喜欢将选定的选项卡存储在窗口的哈希值中。这也允许向看到“相同”页面的同事发送链接。诀窍是在选择另一个选项卡时更改位置的哈希值。如果您已经在页面中使用了 #,则可能需要拆分哈希标签。在我的应用程序中,我使用“:”作为哈希值分隔符。
<ul class="nav nav-tabs" id="myTab">
<li class="active"><a href="#home">Home</a></li>
<li><a href="#profile">Profile</a></li>
<li><a href="#messages">Messages</a></li>
<li><a href="#settings">Settings</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="home">home</div>
<div class="tab-pane" id="profile">profile</div>
<div class="tab-pane" id="messages">messages</div>
<div class="tab-pane" id="settings">settings</div>
</div>
JavaScript, has to be embedded after the above in a <script>...</script>
part.
JavaScript,必须嵌入在上述<script>...</script>
部分之后。
$('#myTab a').click(function(e) {
e.preventDefault();
$(this).tab('show');
});
// store the currently selected tab in the hash value
$("ul.nav-tabs > li > a").on("shown.bs.tab", function(e) {
var id = $(e.target).attr("href").substr(1);
window.location.hash = id;
});
// on load of the page: switch to the currently selected tab
var hash = window.location.hash;
$('#myTab a[href="' + hash + '"]').tab('show');
回答by Xavi Martínez
This is the best one that I tried:
这是我尝试过的最好的一个:
$(document).ready(function() {
if (location.hash) {
$("a[href='" + location.hash + "']").tab("show");
}
$(document.body).on("click", "a[data-toggle='tab']", function(event) {
location.hash = this.getAttribute("href");
});
});
$(window).on("popstate", function() {
var anchor = location.hash || $("a[data-toggle='tab']").first().attr("href");
$("a[href='" + anchor + "']").tab("show");
});
回答by insign
A mix between others answers:
其他答案的混合:
- No jump on click
- Save on location hash
- Save on localStorage (e.g: for form submit)
Just copy&paste ;)
if (location.hash) { $('a[href=\'' + location.hash + '\']').tab('show'); } var activeTab = localStorage.getItem('activeTab'); if (activeTab) { $('a[href="' + activeTab + '"]').tab('show'); } $('body').on('click', 'a[data-toggle=\'tab\']', function (e) { e.preventDefault() var tab_name = this.getAttribute('href') if (history.pushState) { history.pushState(null, null, tab_name) } else { location.hash = tab_name } localStorage.setItem('activeTab', tab_name) $(this).tab('show'); return false; }); $(window).on('popstate', function () { var anchor = location.hash || $('a[data-toggle=\'tab\']').first().attr('href'); $('a[href=\'' + anchor + '\']').tab('show'); });
- 点击不跳转
- 保存位置哈希
- 保存在 localStorage 上(例如:用于表单提交)
只需复制&粘贴;)
if (location.hash) { $('a[href=\'' + location.hash + '\']').tab('show'); } var activeTab = localStorage.getItem('activeTab'); if (activeTab) { $('a[href="' + activeTab + '"]').tab('show'); } $('body').on('click', 'a[data-toggle=\'tab\']', function (e) { e.preventDefault() var tab_name = this.getAttribute('href') if (history.pushState) { history.pushState(null, null, tab_name) } else { location.hash = tab_name } localStorage.setItem('activeTab', tab_name) $(this).tab('show'); return false; }); $(window).on('popstate', function () { var anchor = location.hash || $('a[data-toggle=\'tab\']').first().attr('href'); $('a[href=\'' + anchor + '\']').tab('show'); });
回答by apfz
Xavi's code was allmost fully working. But when navigating to another page, submitting a form, then being redirected to the page with my tabs was not loading the saved tab at all.
Xavi 的代码几乎可以正常工作。但是,当导航到另一个页面,提交表单,然后被重定向到带有我的选项卡的页面时,根本没有加载保存的选项卡。
localStorage to the rescue (slightly changed Nguyen's code):
localStorage 来救援(稍微改变了 Nguyen 的代码):
$('a[data-toggle="tab"]').click(function (e) {
e.preventDefault();
$(this).tab('show');
});
$('a[data-toggle="tab"]').on("shown.bs.tab", function (e) {
var id = $(e.target).attr("href");
localStorage.setItem('selectedTab', id)
});
var selectedTab = localStorage.getItem('selectedTab');
if (selectedTab != null) {
$('a[data-toggle="tab"][href="' + selectedTab + '"]').tab('show');
}
回答by Ajith R Nair
This one use HTML5 localStorage
to store active tab
这个使用 HTML5localStorage
来存储活动标签
$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
localStorage.setItem('activeTab', $(e.target).attr('href'));
});
var activeTab = localStorage.getItem('activeTab');
if (activeTab) {
$('#navtab-container a[href="' + activeTab + '"]').tab('show');
}
ref: http://www.tutorialrepublic.com/faq/how-to-keep-the-current-tab-active-on-page-reload-in-bootstrap.phphttps://www.w3schools.com/bootstrap/bootstrap_ref_js_tab.asp
参考:http: //www.tutorialrepublic.com/faq/how-to-keep-the-current-tab-active-on-page-reload-in-bootstrap.php https://www.w3schools.com/bootstrap /bootstrap_ref_js_tab.asp
回答by Ziad
Basing myself on answers provided by Xavi Martínezand kopporI came up with a solution that uses the url hash or localStorage depending on the availability of the latter:
根据Xavi Martínez和koppor提供的答案,我想出了一个使用 url 哈希或 localStorage 的解决方案,具体取决于后者的可用性:
function rememberTabSelection(tabPaneSelector, useHash) {
var key = 'selectedTabFor' + tabPaneSelector;
if(get(key))
$(tabPaneSelector).find('a[href=' + get(key) + ']').tab('show');
$(tabPaneSelector).on("click", 'a[data-toggle]', function(event) {
set(key, this.getAttribute('href'));
});
function get(key) {
return useHash ? location.hash: localStorage.getItem(key);
}
function set(key, value){
if(useHash)
location.hash = value;
else
localStorage.setItem(key, value);
}
}
Usage:
用法:
$(document).ready(function () {
rememberTabSelection('#rowTab', !localStorage);
// Do Work...
});
It does not keep up with the back button as is the case for Xavi Martínez's solution.
它跟不上后退按钮,就像Xavi Martínez的解决方案一样。
回答by Nguyen Pham
My code, it work for me, I use localStorage
HTML5
我的代码,它对我有用,我使用localStorage
HTML5
$('#tabHistory a').click(function(e) {
e.preventDefault();
$(this).tab('show');
});
$("ul.nav-tabs#tabHistory > li > a").on("shown.bs.tab", function(e) {
var id = $(e.target).attr("href");
localStorage.setItem('selectedTab', id)
});
var selectedTab = localStorage.getItem('selectedTab');
$('#tabHistory a[href="' + selectedTab + '"]').tab('show');
回答by Neil Bannet
I tried this and it works: ( Please replace thiswith the pill or tab you are using )
我试过了,它有效:(请用您正在使用的药丸或标签替换它)
jQuery(document).ready(function() {
jQuery('a[data-toggle="pill"]').on('show.bs.tab', function(e) {
localStorage.setItem('activeTab', jQuery(e.target).attr('href'));
});
// Here, save the index to which the tab corresponds. You can see it
// in the chrome dev tool.
var activeTab = localStorage.getItem('activeTab');
// In the console you will be shown the tab where you made the last
// click and the save to "activeTab". I leave the console for you to
// see. And when you refresh the browser, the last one where you
// clicked will be active.
console.log(activeTab);
if (activeTab) {
jQuery('a[href="' + activeTab + '"]').tab('show');
}
});
I hope it would help somebody.
我希望它会帮助某人。
Here is the result: https://jsfiddle.net/neilbannet/ego1ncr5/5/
回答by Mr. Winson
Well, this is already in 2018 but I think it is better late than never (like a title in a TV program), lol. Down here is the jQuery code that I create during my thesis.
嗯,这已经是 2018 年了,但我认为迟到总比没有好(就像电视节目中的标题一样),哈哈。下面是我在论文中创建的 jQuery 代码。
<script type="text/javascript">
$(document).ready(function(){
$('a[data-toggle="tab"]').on('show.affectedDiv.tab', function(e) {
localStorage.setItem('activeTab', $(e.target).attr('href'));
});
var activeTab = localStorage.getItem('activeTab');
if(activeTab){
$('#myTab a[href="' + activeTab + '"]').tab('show');
}
});
</script>
and here is the code for bootstrap tabs:
这是引导程序选项卡的代码:
<div class="affectedDiv">
<ul class="nav nav-tabs" id="myTab">
<li class="active"><a data-toggle="tab" href="#sectionA">Section A</a></li>
<li><a data-toggle="tab" href="#sectionB">Section B</a></li>
<li><a data-toggle="tab" href="#sectionC">Section C</a></li>
</ul>
<div class="tab-content">
<div id="sectionA" class="tab-pane fade in active">
<h3>Section A</h3>
<p>Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui. Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth.</p>
</div>
<div id="sectionB" class="tab-pane fade">
<h3>Section B</h3>
<p>Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna, ornare id gravida ut, mollis a magna. Aliquam porttitor condimentum nisi, eu viverra ipsum porta ut. Nam hendrerit bibendum turpis, sed molestie mi fermentum id. Aenean volutpat velit sem. Sed consequat ante in rutrum convallis. Nunc facilisis leo at faucibus adipiscing.</p>
</div>
<div id="sectionC" class="tab-pane fade">
<h3>Section C</h3>
<p>Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna, ornare id gravida ut, mollis a magna. Aliquam porttitor condimentum nisi, eu viverra ipsum porta ut. Nam hendrerit bibendum turpis, sed molestie mi fermentum id. Aenean volutpat velit sem. Sed consequat ante in rutrum convallis. Nunc facilisis leo at faucibus adipiscing.</p>
</div>
</div>
</div>
Dont forget to call the bootstrap and other fundamental things
here are quick codes for you:
以下是为您提供的快速代码:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
Now let's come to the explanation:
现在让我们来解释一下:
The jQuery code in the above example simply gets the element's href attribute value when a new tab has been shown using the jQuery .attr() method and save it locally in the user's browser through HTML5 localStorage object. Later, when the user refresh the page it retrieves this data and activate the related tab via .tab('show') method.
上面示例中的 jQuery 代码仅在使用 jQuery .attr() 方法显示新选项卡时获取元素的 href 属性值,并通过 HTML5 localStorage 对象将其本地保存在用户浏览器中。稍后,当用户刷新页面时,它会检索此数据并通过 .tab('show') 方法激活相关选项卡。
Looking up for some examples? here is one for you guys.. https://jsfiddle.net/Wineson123/brseabdr/
寻找一些例子?这是给你们的.. https://jsfiddle.net/Wineson123/brseabdr/
I wish my answer could help you all.. Cheerio! :)
希望我的回答对大家有帮助.. Cheerio!:)
回答by Joeri Landman
Since I cannot comment yet I copied the answer from above, it really helped me out. But I changed it to work with cookies instead of #id so I wanted to share the alterations. This makes it possible to store the active tab longer than just one refresh (e.g. multiple redirect) or when the id is already used and you don't want to implement koppors split method.
由于我还不能发表评论,所以我从上面复制了答案,它确实帮助了我。但是我将其更改为使用 cookie 而不是 #id,因此我想分享更改。这使得可以将活动选项卡存储的时间长于一次刷新(例如多次重定向),或者当 id 已经被使用并且您不想实现 koppors 拆分方法时。
<ul class="nav nav-tabs" id="myTab">
<li class="active"><a href="#home">Home</a></li>
<li><a href="#profile">Profile</a></li>
<li><a href="#messages">Messages</a></li>
<li><a href="#settings">Settings</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="home">home</div>
<div class="tab-pane" id="profile">profile</div>
<div class="tab-pane" id="messages">messages</div>
<div class="tab-pane" id="settings">settings</div>
</div>
<script>
$('#myTab a').click(function (e) {
e.preventDefault();
$(this).tab('show');
});
// store the currently selected tab in the hash value
$("ul.nav-tabs > li > a").on("shown.bs.tab", function (e) {
var id = $(e.target).attr("href").substr(1);
$.cookie('activeTab', id);
});
// on load of the page: switch to the currently selected tab
var hash = $.cookie('activeTab');
if (hash != null) {
$('#myTab a[href="#' + hash + '"]').tab('show');
}
</script>