[英]Why does my code shows error when i Click the button
I am learning javascript. I am creating my notes app, but it's showing error to me.我正在学习 javascript。我正在创建我的笔记应用程序,但它向我显示错误。 Please help to solve it.
请帮助解决它。
let addBtn = document.getElementById('addBtn');
addBtn.addEventListener('click', function(e) {
let addTxt = document.getElementById("addTxt").value;
let notes = localStorage.getItem("notes");
if (notes == null) {
notesObj = [];
} else {
notesObj = JSON.parse(notes);
}
notes.push(addTxt);
localStorage.setItem("notes", JSON.stringify(notes));
addTxt.value = "";
console.log(notes);
console.log("clicked");
})
You should be pushing onto notesObj
, and stringifying that when saving back to localStorage
.您应该推送到
notesObj
,并在保存回localStorage
时将其字符串化。
Also, addTxt
is a string, not the input element.此外,
addTxt
是一个字符串,而不是输入元素。 To clear out the input element, you need to set the vaslue of the element, not the string.要清除输入元素,您需要设置元素的值,而不是字符串。
let addBtn = document.getElementById('addBtn'); addBtn.addEventListener('click', function(e) { let addTxt = document.getElementById("addTxt").value; let notes = localStorage.getItem("notes"); if (notes == null) { notesObj = []; } else { notesObj = JSON.parse(notes); } noteObjs.push(addTxt); localStorage.setItem("notes", JSON.stringify(notesObj)); document.getElementById("addTxt").value = ""; console.log(notes); console.log("clicked"); })
As said in comments: push into the parsed Array, not into the LS retrieved String.正如评论中所说: 推入已解析的数组,而不是推入 LS 检索到的字符串。
Here's a nicer remake:这是一个更好的翻拍:
// DOM utility functions:
const EL = (sel, par) => (par || document).querySelector(sel);
// Task:
const EL_add = EL("#addBtn");
const EL_txt = EL("#addTxt");
EL_add.addEventListener("click", (evt) => {
// Prevent default browser action
evt.preventDefault();
// Trim your values from spaces!
const addTxt = EL_txt.value.trim();
// No text, do nothing
if (!addTxt) return;
// Get nodes from LS or fallback to empty Array
const notesArr = JSON.parse(localStorage.notes || "[]");
// Add note
notesArr.push(addTxt);
// Save note
localStorage.notes = JSON.stringify(notesArr);
// Reset input value
EL_txt.value = "";
})
Firstly, notes is a string, which is fine.首先,notes 是一个字符串,这很好。 But is notesObj an array or an object?
但是 notesObj 是数组还是 object? if it notes is null, it is an array, but otherwise it is an object. This inconsistency makes
notes.push(addTxt)
which is only available to array.如果 notes 是 null,它是一个数组,否则它是一个 object。这种不一致使得
notes.push(addTxt)
只能用于数组。 When there is stuff in localStorage, there is no push
function for object, so it will make an error.当localStorage有东西的时候,object没有
push
function,所以会报错。 To fix, make a property on the notes object, such as 'data', which you can then do notesObj.data.push(txt)
, also, when the object is null, turn it into a {data:[]}
要修复,请在注释 object 上创建一个属性,例如“数据”,然后您可以执行
notesObj.data.push(txt)
,此外,当 object 为 null 时,将其转换为{data:[]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.