【问题标题】:Uncaught TypeError: Cannot read properties of undefined (reading 'setItem')未捕获的类型错误:无法读取未定义的属性(读取“setItem”)
【发布时间】: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,这将是一个惊人的论点。

标签: javascript local-storage


【解决方案1】:

您已将“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)';
}

希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 2021-12-22
    • 2021-12-25
    • 2021-11-24
    • 2021-10-31
    • 2021-11-07
    • 2022-01-17
    • 2023-03-13
    • 2022-01-01
    • 1970-01-01
    相关资源
    最近更新 更多