Javascript closure in for loop

0

What I want is to go through the matrix material and generate a div for each element and that in the first div put elemento1 , in the second elemento2 etc.

This is what I have:

var material = [{nombre: 'elemento1'},{nombre: 'elemento2'},{nombre: 'elemento3'}]

var longitud = material.length; i=0;

for(i; i<longitud; i++){
    $("#lista-material").append(' <a href="#"><div class="item col-xs-6 col-ms-3 col-md-3 col-xl-3"></div></a>');                   
    $(".item").html(material[i].nombre);

};

The result I hope for is:

div1.innerHTML = elemento1
div2.innerHTML = elemento2
div3.innerHTML = elemento3

The result I get is:

div1.innerHTML = elemento3
div2.innerHTML = elemento3
div3.innerHTML = elemento3

Code clarifications: #lista-material is a container where all divs are generated.

    
asked by Pablo 21.03.2017 в 14:20
source

1 answer

0

The problem is in the following line of code:

$(".item").html(material[i].nombre);

This code selects all div of previously generated .item and sets them to the last value of the array.

Here is a jsfiddle where the error is reproduced.

Solution:

To solve it you can, for example, put% of the item as% and select that id instead of class id :

var material = [{nombre: 'elemento1'},{nombre: 'elemento2'},{nombre: 'elemento3'}]

var longitud = material.length;

for(var i=0; i<longitud; i++){
console.log(material[i].nombre);
    $("#lista-material").append(' <a href="#"><div id="'+material[i].nombre+'" class="item col-xs-6 col-ms-3 col-md-3 col-xl-3"></div></a>');                   
    $('#' + material[i].nombre).html(material[i].nombre);

};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>

</p>

<div id="lista-material">
</div>
    
answered by 21.03.2017 / 14:40
source