[英]stay in the same tab after refreshing page
我有一个页面,其中包含相同的 url,但在单击选项卡后有很多选项卡,我可以看到其内容,但在我刷新页面选项卡 (0) 后立即出现,但我想要上次使用的选项卡。 我怎样才能做到这一点。 这是js代码
<script>
const tabBtn = document.querySelectorAll(".tab");
const tab = document.querySelectorAll(".tabShow");
function tabs(panelIndex){
tab.forEach(function(node){
node.style.display="none";
});
tab[panelIndex].style.display="block";
}
tabs(0);
$(".tab").click(function(){
$(this).addClass("active").siblings().removeClass("active");
});
</script>
您可以创建一个每次更改选项卡时都会更新的变量,然后检查该变量等于什么以确定默认情况下应打开哪个选项卡。
您可以使用Session Storage或Query 参数(搜索参数)或Hash 参数
会话存储:可以通过键存储一些值,直到选项卡关闭
哈希参数:数据存储在 url 中。 您甚至可以将 url 保存在某处或共享它,当它打开时,将打开所需的选项卡
查询参数:与哈希参数相同,但更改时整个页面刷新
会话存储解决方案:
<script>
const tabButtons = document.querySelectorAll(".tab");
const tabs = document.querySelectorAll(".tabShow");
const changeTab = (tabIndex) => {
sessionStorage.setItem('currentTab', tabIndex);
tabs.forEach((node) => { node.style.display = "none"; });
tabButtons.forEach((tb) => tb.classList.remove('active'));
tabs[tabIndex].style.display = "block";
tabButtons[tabIndex].classList.add('active');
}
tabButtons.forEach((tabButton, index) => {
tabButton.onclick = () => changeTab(index)
});
changeTab(sessionStorage.getItem('currentTab') || 0);
</script>
哈希参数解决方案:
<script>
const tabButtons = document.querySelectorAll(".tab");
const tabs = document.querySelectorAll(".tabShow");
const changeTab = (tabIndex) => {
window.location.hash=`tab=${tabIndex}`;
tabs.forEach((node) => { node.style.display = "none"; });
tabButtons.forEach((tb) => tb.classList.remove('active'));
tabs[tabIndex].style.display = "block";
tabButtons[tabIndex].classList.add('active');
}
tabButtons.forEach((tabButton, index) => {
tabButton.onclick = () => changeTab(index)
});
const hash = new URLSearchParams(location.hash.slice(1));
changeTab(hash.get('tab') || 0);
</script>
查询参数解决方案
与哈希参数解决方案相同,但使用search
而不是hash
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.