【发布时间】:2022-01-10 04:31:30
【问题描述】:
我想用 javascript 创建一个简单的明暗模式系统。它通过在 Window.localStorage 中设置“darkTheme”布尔值来工作 这是我写的代码:
let lightThemeCheckbox = document.getElementById('lightThemeCheckbox');
let body = document.body;
updateLightTheme();
lightThemeCheckbox.addEventListener('change', function() {
Window.localStorage.setItem('darkTheme', this.checked);
});
function updateLightTheme() {
let darkTheme = window.localStorage.getItem('darkTheme');
if(darkTheme == undefined) {
body.style.backgroundColor = 'rgb(255, 255, 255)';
return;
}
body.style.backgroundColor = darkTheme ? 'rgb(100, 100, 100)' : 'rgb(255, 255, 255)';
}
但由于某种原因,我收到此错误:
Uncaught TypeError: Cannot read properties of undefined (reading 'setItem')
at HTMLInputElement.<anonymous> (header.js:7)
(anonymous) @ header.js:7
谁能帮忙?
【问题讨论】:
-
没有静态的
localStorage属性。你的意思是window.localStorage。但这是一个有趣的点:你是从MDN docs 的标题中得到Window.localStorage的概念吗?像所有 ECMAScript 原生 API 一样,通过拉取请求最终将其更改为Window.prototype.localStorage,这将是一个惊人的论点。