Uncaught TypeError: Cannot read properties of undefined (reading 'setItem')

Uncaught TypeError: Cannot read properties of undefined (reading 'setItem')

我想用 javascript 创建一个简单的 light/dark 模式系统。它通过在 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

有人能帮忙吗?

您已将“window”大写 w。您可以使用以下内容:

使用小写window

const lightThemeCheckbox = document.getElementById('lightThemeCheckbox');
const body = document.body;

updateLightTheme();

lightThemeCheckbox.addEventListener('change', () => {
    window.localStorage.setItem('darkTheme', this.checked);
});

function updateLightTheme() {
    const 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)';
}

使用 localStorage 不使用 window

const lightThemeCheckbox = document.getElementById('lightThemeCheckbox');
const body = document.body;

updateLightTheme();

lightThemeCheckbox.addEventListener('change', () => {
    localStorage.setItem('darkTheme', this.checked);
});

function updateLightTheme() {
    const darkTheme = 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)';
}

希望对您有所帮助!