Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

252
Vistas
El almacenamiento local no funciona correctamente para JS onclick

Mi almacenamiento local funciona en términos de decir verdadero y falso, pero cuando se actualiza la página, revierte pero mantiene el valor. Por ejemplo, si cambio del modo oscuro predeterminado (falso) al modo claro (verdadero), se muestra como verdadero en el almacenamiento local (lo cual es bueno). Sin embargo, cuando actualizo la página, aunque el valor sigue siendo verdadero, la página ha vuelto a su valor predeterminado (falso).

HTML:

 <body onload="stored()"> <label for="ID_HERE" class="toggle-switchy"> <input checked type="checkbox" name="server" id="ID_HERE" /> <span class="toggle" onclick="toggle()" id="saveDarkLight"></span> <span class="switch"></span> </label> </body>

JS:

 function stored() { var storedValue = localStorage.getItem("server"); if (storedValue) { lightmode() document.getElementById("ID_HERE").checked = true; } else { darkmode() document.getElementById("ID_HERE").checked = false; } } function toggle() { if (document.getElementById("ID_HERE").checked) { lightmode() var input = document.getElementById("ID_HERE"); localStorage.setItem("server", input.checked); } else { darkmode() var input = document.getElementById("ID_HERE"); localStorage.setItem("server", input.checked); } } function darkmode() { const bodyChanges = document.querySelectorAll('.margin_body'); for (let i = 0; i < bodyChanges.length; i++) { bodyChanges[i].style.background = '#0c0a0f'; } } function lightmode() { const bodyChanges = document.querySelectorAll('.margin_body'); for (let i = 0; i < bodyChanges.length; i++) { bodyChanges[i].style.background = 'white'; } }
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

localStorage solo guarda valores de string , por lo que guardar true o false lo convertirá en 'true' o 'false' . Cuando vuelva a leer, debe JSON.parse . analizarlo o verificar los valores de cadena.

 function stored() { const storedValue = localStorage.getItem("server"); if(storedValue === 'true'){ // <------ lightmode() document.getElementById("ID_HERE").checked = true; }else{ darkmode() document.getElementById("ID_HERE").checked = false; } }
about 4 years ago · Juan Pablo Isaza Denunciar

0

En primer lugar, creo que querrá el controlador de eventos onclick en el elemento de entrada.

Además, la siguiente es una implementación rápida y sucia:

JS:

 const SAVED_USER_INPUT = "savedUserInput"; const TARGET_ID = "toggle-text"; const BLUE = "blue"; const RED = "red"; const text = { [BLUE]: "Text color currently set to blue (default/unchecked state). Click to change to red", [RED]: "Text color currently set to red. Click to change to blue", }; const handleToggle = (event) => { const isChecked = event.target.checked; const color = isChecked ? RED : BLUE; setColor(color); setText(color); savePreference(color); }; const setColor = (fontColor = BLUE) => { document.getElementById(TARGET_ID).style.color = fontColor; return true; }; const setText = (color) => { document.getElementById(TARGET_ID).innerText = text[color]; return true; }; const setChecked = (color) => { if (color === RED) { document.getElementsByTagName("input")[0].setAttribute("checked", true); } }; const savePreference = (color) => localStorage.setItem(SAVED_USER_INPUT, color); const getSavedPreference = () => localStorage.getItem(SAVED_USER_INPUT); // localStorage.clear() window.onload = () => { if (!(getSavedPreference() === null)) { const savedColor = getSavedPreference(); setColor(savedColor); setText(savedColor); setChecked(savedColor); } else { setColor(); setText(BLUE); setChecked(BLUE); } };

HTML:

 <!DOCTYPE html> <html> <head> <title>localStorage</title> <script src="app.js"></script> </head> <body> <label> <input type="checkbox" onclick="handleToggle(event)"> <span id="toggle-text"></span> </span> </label> </body> </html>
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda