我具有以下标签设置:
<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 = function() {
alert("clicked back button");
}; history.pushState({}, '');
window.onpopstate
函数可在所有其他页面上使用,除非我尝试在搜索后返回标签页。我猜测由于某种原因无法识别标签。
关于如何进行这项工作的任何想法?
答案 0 :(得分:0)
在文档准备功能中尝试类似的操作:
$(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');
}
});
});