如何在用户关闭网页时删除 link 颜色的本地存储

How to remove the local storage of a link colour when user closes the web page

我知道之前有人问过类似的问题,但该解决方案会在页面刷新时清除本地存储。 我有一个本地存储来显示哪个 link 当前处于活动状态,这样即使页面已刷新,用户也知道最后按下了哪个菜单选项。


  
  /*===== LINK ACTIVE  =====     keeps the colour in the clicked link even after refresh*/
  const linkColor = document.querySelectorAll('.nav__link')
  
  function colorLink() {
    linkColor.forEach(l => l.classList.remove('active'))
    this.classList.add('active')
    
    // Added this to read data attribute
    let this_index = this.getAttribute("data-nav_link_index")
    localStorage.setItem("active_nav_link", this_index)
  }
  linkColor.forEach((l,i) => {
    l.addEventListener('click', colorLink);
    
    // Added this to set data attribute
    l.setAttribute("data-nav_link_index", i);
    
    // Added this to add the active class
    if(localStorage.getItem("active_nav_link")==i){
      l.classList.add("active");
    }else if(localStorage.getItem("active_nav_link")!==null){
      l.classList.remove("active");
    }
  })
  
 

现在,当我登录主仪表板页面时,颜色仍保留在上次单击的菜单中。有没有一种方法可以在退出页面时清除此颜色,以便用户在登录时看不到任何颜色。非常感谢您的宝贵时间。

尝试 localStorage.removeItem("active_nav_link") 登录

您可以使用会话存储而不是本地存储。

关闭标签页或浏览器时会清除会话存储。

  • 如果你想从 localStorage 中清除项目,只需使用 localStorage.removeItem('item'),如果你想清除所有项目,只需使用 localStorage.clear(),如果你想在用户离开页面时删除该项目,请使用window.onunload 事件