0

i am doing a bucle for to get the keys from local storage archives and i want to attach that keys to dynamically created elements the way that when i click over the new created element (who recives the name of the storage file) it will alert the content. This is what i have, the problem is in archivo[ keys[i] ].

function local(){
    archivo = {};
    keys = Object.keys(localStorage);
    i = 0; var key;


    for (i = 0; key = keys[i] ; i++) {

    var compra_recuperada = document.createElement('ons-list-item');

    compra_recuperada.innerHTML = keys[i];                                            
    document.getElementById('compra').appendChild(compra_recuperada); 
    archivo[ keys[i] ] = localStorage.getItem( keys[i] ); 
compra_recuperada.addEventListener('click', function(){ alert(archivo[ keys[i] ])  
})}}; 
Fuzz
  • 39
  • 4
  • 2
    Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – melpomene Apr 24 '19 at 16:35
  • I think that with my simplification i expressed something different, i edit and post my real problem now. – Fuzz Apr 24 '19 at 17:21
  • 1
    Not really, you're still trying to use a loop variable (`i`) inside a callback and need to use a closure to solve. – Heretic Monkey Apr 24 '19 at 17:36

1 Answers1

0

Remove the declaration of variable i outside of the loop and change for (i = 0; key = keys[i] ; i++) to for (let i = 0; key = keys[i]; i++) should work for your case.

In the previous version, each element shares the same variable i. By the time you see the alert, it is already changed to the last value. The second version will create a new variable for each loop iteration thanks to the ES6 let keyword.

jian
  • 1,236
  • 11
  • 11