Javascript:单击浏览器后退按钮后检测动态选项卡
我有以下选项卡设置:Javascript:单击浏览器后退按钮后检测动态选项卡,javascript,bootstrap-tabs,Javascript,Bootstrap Tabs,我有以下选项卡设置: <ul class="nav nav-tabs" id="myTab"> <li class="active"><a href="#search">Search</a></li> <li><a href="#search_other">Search other</a></li> </ul> <div class="tab-content"&
<ul class="nav nav-tabs" id="myTab">
<li class="active"><a href="#search">Search</a></li>
<li><a href="#search_other">Search other</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="search">
<%= render 'search/search' %>
</div>
<div class="tab-pane" id="search_other">
<%= render 'results/search_other' %>
</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);
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');
</script>
<script>
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
history.pushState(null, null, $(this).attr('href'));
});
</script>
window.onpopstate
功能从其他页面开始工作,搜索后试图返回选项卡页面时除外。我猜是因为某种原因,它不认识这个账单。
关于如何实现这一点,您有什么想法吗?在document ready(文档准备)功能中,尝试以下方法:
window.onpopstate = function() {
alert("clicked back button");
}; history.pushState({}, '');
$(document).ready(function(){
$('a[data-toggle="tab"]').on('show.bs.tab', function(e) {
localStorage.setItem('activeTab', $(e.target).attr('href'));
});
var activeTab = localStorage.getItem('activeTab');
if(activeTab){
$('#myTab a[href="' + activeTab + '"]').tab('show');
}
});
window.popstate的代码:
$(document).ready(function() {
// add a hash to the URL when the user clicks on a tab
$('a[data-toggle="tab"]').on('click', function(e) {
history.pushState(null, null, $(this).attr('href'));
});
// navigate to a tab when the history changes
window.addEventListener("popstate", function(e) {
var activeTab = $('[href=' + location.hash + ']');
if (activeTab.length) {
activeTab.tab('show');
} else {
$('.nav-tabs a:first').tab('show');
}
});
});
为什么不使用localStorage存储活动选项卡以供参考。感谢@Srinivas.的回复。。您能否更具体地说明如何实现
localStorage
,然后实现窗口.onpopstate
?不幸的是,这也不起作用。我在窗口中添加了您的代码。onpopstate
和警报显示在我单击浏览器后退按钮的任何页面上,但我想从搜索结果返回到选项卡时除外。我已根据您的方法更新了答案。您能否在codepen或jsbin中创建一个示例,以便更容易地解决问题