如何在重新加载页面后保留在选定的选项卡中

How to remain in the tab selected after reloading the page

本文关键字:保留 选项 新加载 加载      更新时间:2023-09-26

我正在开发一个网页。在一个页面中,我们有 3 个选项卡 A B 和 C.每个选项卡都包含一些带有动态内容的表和一个用于重新加载页面的刷新按钮(这里我们使用 window.location.reload(),因为我们从数据模型中获取数据作为单个转储)。

面临的问题是,即使我重新加载选项卡 C,我的页面也会返回到选项卡 A。我需要一种方法来存储哪个选项卡在重新加载之前处于活动状态的状态。

该选项卡在 ID 为"大型机"的 iframe 中调用.HTML:

<ul class="tabs">
<li>
<input type="radio" name="tabs" id="tab1" checked />
<label for="tab1">Tab A</label>
<div id="tab-content1" class="tab-content">
<div class="btn-div">
<input type="button" value="Refresh" onclick="refresh();">
</div>
<table class="x_table" >
</table>
</li>
<li>
<input type="radio" name="tabs" id="tab1" checked />
<label for="tab1">Tab B</label>
<div id="tab-content1" class="tab-content">
<div class="btn-div">
<input type="button" value="Refresh" onclick="refresh();">
</div>
<table class="x_table" >
</table>
</li>
<li>
<input type="radio" name="tabs" id="tab1" checked />
<label for="tab1">Tab C</label>
<div id="tab-content1" class="tab-content">
<div class="btn-div">
<input type="button" value="Refresh" onclick="refresh();">
</div>
<table class="x_table" >
</table>
</li>
</ul>

脚本:

$(function(){
$(window ).unload(function() {
sessionStorage.setItem("tab1", $('#tab1').checked);
sessionStorage.setItem("tab2", $('#tab3').checked);
sessionStorage.setItem("tab3", $('#tab3').checked);
});
$(window).load(function() {
if (tab1){
document.getElementById("tab1").checked="true";
} else if (tab2){
document.getElementById("tab2").checked="true";
} else if (tab3){
document.getElementById("tab3").checked="true";
}
});
});

提前致谢

将活动选项卡状态存储在会话、本地存储或作为 http 请求参数中,并基于该参数在页面加载时隐藏/显示选项卡内容。例如,如果它是 localStorage,那么,使用:

重新加载页面之前: localStorage.setItem("ActiveTabID" , "tab2");

然后在加载时:

$(window).load(function() {
   var activeTab = localStorage.getItem("ActiveTabID");
   if(activeTab=="tab1"){
      $('#tab1Content').show();
      $('#tab2Content').hide();
      $('#tab3Content').hide();
   }else if(activeTab=="tab2"){
      $('#tab2Content').show();
      $('#tab1Content').hide();
      $('#tab3Content').hide();
   }

同样,tab3,还显示它是否处于活动状态。