Javascript 如何使用JS跨多个会话存储用户选择?
我有两个简单的CSS表:Javascript 如何使用JS跨多个会话存储用户选择?,javascript,html,css,Javascript,Html,Css,我有两个简单的CSS表: 违约 暗模式 我有一个按钮,它调用一个函数onClick在两张表之间切换。我目前正在编写一个代码,将用户的选择存储在cookie(或本地存储)中,但我不确定如何进行 function setTheme() { let theme = document.getElementsByTagName('link')[0]; if (theme.getAttribute('href') == 'default.css') { theme.set
- 违约
- 暗模式
function setTheme() {
let theme = document.getElementsByTagName('link')[0];
if (theme.getAttribute('href') == 'default.css') {
theme.setAttribute('href', 'darkmode.css');
} else {
theme.setAttribute('href', 'default.css');
}
}
我曾尝试在代码末尾添加一个localStorage集,但它就是不起作用。为此,我不想使用jQuery,而是坚持使用Javascript。我还希望它在多个会话中保持持久性,而不管浏览器是否关闭。
document.getElementById('theme').addEventListener('change',setTheme)
函数applyTheme(){
const theme=localStorage.getItem('theme'))
如果(主题){
const link=document.getElementsByTagName('link')[0]
link.setAttribute('href',主题)
}
}
函数集合主题(事件){
localStorage.setItem('theme',event.target.value)
applyTheme()
}
违约
黑暗的
那么您在本地存储方面做了哪些尝试?在cookies方面也做了哪些尝试?您有可以管理会话的服务器吗?你可以把它放在那里。