1

I am generating some elements after receiving a JSON. Those elements with classname "tipoGenero" have some CSS. I want that when any of those elements are clicked, display the value of the <span>. However, it works and generates the events, but whatever element I click I only get the value of the last one.

for (var i = 0; i < parsedText.length; i++) {
    dato += "<div class='tipoGenero'>";
    dato += "<img src=/logos/" + parsedText[i].imagen + ">";
    dato += "<span>" + parsedText[i].nombre + "</span>";
    dato += "</div>";
} 
document.getElementById('generos').innerHTML = dato;
//generates events for class items 
var classname = document.getElementsByClassName("tipoGenero");
for (var i = 0; i < classname.length; i++) {
    valor = classname[i].children[1].textContent;
    alert(valor);
    classname[i].addEventListener('click', function() { myFunction(valor); }, false);
}

function myFunction(text) {
    alert(text);
}
Regent
  • 5,142
  • 3
  • 21
  • 35
Alpha2k
  • 2,212
  • 7
  • 38
  • 65
  • that's because the `valor` variable reference that you pass to myFunciton passes the value that's referenced in valor variable at the time of myFunction execution. This variable at that time holds the text value of your last element. – gp. Jan 16 '15 at 11:00

1 Answers1

1

You have to save the current value of 'valor' in your listener: could do it like this :

classname[i].addEventListener('click', function(val){
    return function(){
        myFunction(val);
    };
})(valor), false);
Hacketo
  • 4,978
  • 4
  • 19
  • 34