首页 > 解决方案 > 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功能适用​​于所有其他页面,除非我在搜索后尝试返回标签页。我猜出于某种原因它无法识别标签。关于如何使这项工作的任何想法?

标签: javascriptbootstrap-tabs

解决方案


在文档就绪功能中尝试这样的事情:

$(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');
    }
  });
});

推荐阅读