【问题标题】:How do I keep the active tab after page refresh with localStorage?如何在使用 localStorage 刷新页面后保持活动选项卡?
【发布时间】:2022-01-02 11:34:25
【问题描述】:
  // show the section active
  $('div>a').click(function() {
    console.log($(this).attr('id'))
    $('.main.container>section').removeClass('active')
    $('.main.container>section.' + $(this).attr('id')).addClass('active')
  })

我想让此代码与 localstorage 一起使用,以便它在页面刷新后显示活动选项卡。 我在stackoverflow中尝试过其他人,但它们不适用于我的情况。也许我没有完全理解 localstorage 的事情。请让我知道是否有另一种方法可以使它工作。任何帮助都会得到满足。

这是我一直在练习的网址。 https://jsfiddle.net/fnx5y4h8/

【问题讨论】:

    标签: javascript jquery refresh


    【解决方案1】:

    您可以在选择选项卡时设置名为“选项卡”的本地存储项。然后,每当页面加载时,检查该 localStorage 项是否存在。如果是,请选择该选项卡。

    // show the section active
    $('div>a').click(function() {
      selectTab($(this).attr('id'));
      localStorage.setItem("tab", $(this).attr('id'))
    })
    
    // On load
    const loadedTab = localStorage.getItem("tab");
    if (loadedTab) {
      selectTab(loadedTab);
    }
    
    function selectTab(tabId) {
      $('.main.container>section').removeClass('active')
      $('.main.container>section.' + tabId).addClass('active')
    }
    

    【讨论】:

    • 成功了。谢谢!
    猜你喜欢
    • 2020-08-30
    • 1970-01-01
    • 2021-02-15
    • 2020-10-02
    • 2017-07-26
    • 2015-06-16
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多