[英]stay in the same tab after refreshing page
I have a page which contains same url but a lot of tabs after I click on a tab I can see its content but right after I refresh the page tab(0) appear but I want the last used tab.我有一个页面,其中包含相同的 url,但在单击选项卡后有很多选项卡,我可以看到其内容,但在我刷新页面选项卡 (0) 后立即出现,但我想要上次使用的选项卡。 how can I do that.我怎样才能做到这一点。 this is the js code这是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>
您可以创建一个每次更改选项卡时都会更新的变量,然后检查该变量等于什么以确定默认情况下应打开哪个选项卡。
You can use Session Storage or Query parameters (search parameters) or Hash parameters您可以使用Session Storage或Query 参数(搜索参数)或Hash 参数
Session Storage : can store some values by keys until the tab is closed会话存储:可以通过键存储一些值,直到选项卡关闭
Hash Parameters : data is stored in the url.哈希参数:数据存储在 url 中。 You can even save the url somewhere or share it, and when it is open the required tab will be opened您甚至可以将 url 保存在某处或共享它,当它打开时,将打开所需的选项卡
Query Parameters : the same as Hash Parameters but when changed the whole page refreshes查询参数:与哈希参数相同,但更改时整个页面刷新
Session Storage solution:会话存储解决方案:
<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>
Hash Parameters solution:哈希参数解决方案:
<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>
Query Parameters solution查询参数解决方案
The same as Hash Parameters solution, but with search
instead of hash
与哈希参数解决方案相同,但使用search
而不是hash
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.