javascript - Javascript:单击浏览器后退按钮后检测动态选项卡
问题描述
我有以下选项卡设置:
<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
功能适用于所有其他页面,除非我在搜索后尝试返回标签页。我猜出于某种原因它无法识别标签。关于如何使这项工作的任何想法?
解决方案
在文档就绪功能中尝试这样的事情:
$(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');
}
});
});
推荐阅读
- excel - 使用索引和匹配函数来匹配行
- rest - 如何使用 SSE (TwinCAT3) 将数据从 Firebase REST API 流式传输到 Beckhoffs 的 PLC?
- mongodb - 使用带有嵌套文档值的 MongoDB .findOne() 函数
- javascript - Vue路由器生产问题
- amazon-web-services - 如何在云端自定义源请求策略中将授权标头列入白名单
- azure-devops - 排他锁 - 超时
- java - 创建初始重复数据的二维字符串数组的最有效方法是什么?
- python - 通过使用 ctypes 调用从 C 函数返回的意外整数
- r - 将 ggplot 规范块合并为单个函数,以应用于多个数据集
- javascript - vue过渡组动画卡住