![](/img/trans.png)
[英]How to send auth token from local storage to the backend with the request when the user clicks a link
[英]How to remove the local storage of a link colour when user closes the web page
我知道以前有人問過類似的問題,但是該解決方案會在頁面刷新時清除本地存儲。 我有一個本地存儲來顯示哪個鏈接當前處於活動狀態,以便用戶知道最后一次按下哪個菜單選項,即使頁面被刷新。
/*===== 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")
您可以使用 session 存儲而不是本地存儲。
Session 存儲在選項卡或瀏覽器關閉時被清除。
localStorage.removeItem('item')
;如果您想清除所有項目,請使用localStorage.clear()
;如果您想在用戶離開頁面時刪除該項目,請使用window.onunload
事件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.