He desarrollado una aplicación de tareas pendientes. donde el usuario inserta algunos valores y se guarda en la pantalla. ahora quiero guardar los valores en el almacenamiento local. Pero no se está guardando, sino que obtengo un {} vacío.
aquí está el código javascript
//crete element from input box and delete let knoo = document.getElementById('kno') let box= document.getElementById('txt') let sub= document.getElementById('sub').addEventListener('click',()=>{ let para = document.createElement('ul') para.innerText= box.value knoo.appendChild(para) box.value='' localStorage.setItem('key', JSON.stringify(para)) //styling para.addEventListener('click', ()=>{ para.style.textDecoration = 'line-through' }) //delete para.addEventListener('dblclick', ()=>{ knoo.removeChild(para) }) })aquí está el html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h2>hi</h2> <div id="hello"> <h1>hello</h1> </div> <button id="btn">delete</button> <br> <br> <input type="text" id="txt"> <button type="submit" id="sub">+</button> <div id="kno"></div> <script src="main.js"></script> </body> </html>Esto se debe a que usa JSON.stringify con un elemento html que no funcionará y siempre producirá {} .
El método JSON.stringify() convierte un objeto o valor de JavaScript en una cadena JSON
La solución es usar una array para almacenar el valor de para y usar JSON.stringify para la array
let knoo = document.getElementById('kno') let box= document.getElementById('txt') let storedvalue = [] if(localStorage.getItem('key')){ storedvalue = localStorage.getItem('key'); } let sub= document.getElementById('sub').addEventListener('click',()=>{ let para = document.createElement('ul') para.innerText= box.value knoo.appendChild(para) box.value='' storedvalue.push(para.innerText) localStorage.setItem('key', JSON.stringify(storedvalue)) //styling para.addEventListener('click', ()=>{ para.style.textDecoration = 'line-through' }) //delete para.addEventListener('dblclick', ()=>{ knoo.removeChild(para) }) }) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h2>hi</h2> <div id="hello"> <h1>hello</h1> </div> <button id="btn">delete</button> <br> <br> <input type="text" id="txt"> <button type="submit" id="sub">+</button> <div id="kno"></div> <script src="main.js"></script> </body> </html>