首页 > 解决方案 > 未捕获的类型错误:无法在笔记网站中读取 HTMLButtonElement 处的 null 属性“推送”

问题描述

我在哪里犯了他的代码错误,因为它返回一个错误:

未捕获的类型错误:无法在 HTMLButtonElement 处读取 null 的属性“推送”。(app.js:15)

console.log("Welcome to Notes Taking Website");

// If user adds a note, add it to the local Storage

let addBtn = document.getElementById('addBtn');
addBtn.addEventListener("click", function(e) {
    let addTxt = document.getElementById("addTxt");
    let notes = localStorage.getItem("notes");
    if (notes == null) {
        notesObj = [];
    } else {
        notesObj = JSON.parse(notes);
    }
    notesObj.push(addTxt.value);
    localStorage.setItem("notes", JSON.stringify(notes));
    addTxt.value = "";
    console.log(notesObj);

})

标签: javascriptarraysdomlocal-storage

解决方案


这是因为你的 localStorage 上已经有一些东西了。这里 else 语句正在执行,并且在 else 语句中创建了数组,所以你得到这个错误。

先清除localStorage

 localStorage.clear(); 

现在可以正常工作了。


推荐阅读