tengo este codigo:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="./framework.js"></script> </head> <body> <p f-text="name"></p> <script> Framework.store('name', 'Joe'); </script> </body> </html>
document.querySelectorAll('*').forEach((element) => { if (element.hasAttribute('f-text')) { const textValue = element.getAttribute('f-text'); element.innerHTML = window.fStore[textValue]; } }); window.Framework = { store: (key, value = '') => { if (value === '') { return window.fStore[key]; } window.fStore[key] = value; } }
Pero recibe este error:
TypeError: Cannot set properties of undefined (setting 'name') at Object.store (/framework.js:15:24) at /:12:15
Quiero que la página represente a 'Joe' obteniendo la clave de f-text
, encontrando el valor de la clave en window.fStore
, luego configurando element.innerHTML
como el valor. Framework.store()
toma una clave y un valor, si no hay ningún valor, devuelve el valor de la clave en window.fStore
, si lo hay, establece window.fStore[key]
en el valor.
Primero debe verificar si window.fStore
existe.
window.Framework = { store: (key, value = '') => { if(!window.fStore) window.fStore = {} if (value === '') { return window.fStore[key]; } window.fStore[key] = value; } } Framework.store('name', 'Joe'); document.querySelectorAll('*').forEach((element) => { if (element.hasAttribute('f-text')) { const textValue = element.getAttribute('f-text'); element.innerHTML = window.fStore[textValue]; } });
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p f-text="name"></p> </body> </html>
Es posible que también deba esperar hasta que se cargue la ventana primero. Algunos navegadores te darán dolor de cabeza si no lo haces
window.addEventListener('load', e=>{ window.Framework = { store: (key, value = '') => { if(!window.fStore) window.fStore = {}; if (value === '') return window.fStore[key]; window.fStore[key] = value; } } window.Framework.store('name', 'Joe'); document.querySelectorAll('*').forEach((element) => { if (element.hasAttribute('f-text')) element.innerHTML = window.fStore[element.getAttribute('f-text')]; }); }