Creé el siguiente código para agregar mi valor de txt a localStorage. Puedo agregar el valor con este código, pero hay un poco más de requisitos para mí. Necesito obtener diferentes valores de txt1 como diferentes elementos en la cadena de almacenamiento local. Con este código, solo obtengo un elemento en localStorage que dice length1 (no importa qué tan largo sea el txt1. ¿Alguien puede ayudarme a resolver el problema de cómo puedo cambiar la longitud del almacenamiento local usando los valores txt1?
let btn1= document.getElementById("btn1"); btn1.addEventListener("click",function(e){ let txt1= document.getElementById("txt1").value; let notes=localStorage.getItem("notes").value; const notesObj={txt1:txt1} window.localStorage.setItem("notes",JSON.stringify(notesObj));Simplemente está actualizando la clave txt1 en su objeto, pero como necesita almacenar múltiples valores, debe usar como matriz. He aquí un pequeño ejemplo:
// Initializing an array with value 1 localStorage.setItem("notes", JSON.stringify({ txt1: [1] })) let txt1 = 2; let notes = JSON.parse(localStorage.getItem("notes")); // Updating my next value of txt1, so that it appends to the array notes.txt1.push(txt1); localStorage.setItem("notes", JSON.stringify(notes)) // Your output is: txt1: [1, 2] console.log(JSON.parse(localStorage.getItem("notes")))En su código, puede hacer lo siguiente:
// Initialize empty array localStorage.setItem("notes", JSON.stringify({ txt1: [] })); let btn1 = document.getElementById("btn1"); btn1.addEventListener("click", function (e) { // When the button is clicked, get the local storage data, and append the new text value let notes = JSON.parse(localStorage.getItem("notes")); notes.txt1.push(document.getElementById("txt1").value); localStorage.setItem("notes", JSON.stringify(notes)) console.log(JSON.parse(localStorage.getItem("notes"))) });