Setting separate function parameters in javascript with addEventListener to have unique ids

StackOverflow https://stackoverflow.com/questions/19735809

  •  03-07-2022
  •  | 
  •  

Frage

I have a for loop that generates elements into a div, and I want to have each element calling the same function but with an unique id.

for(var i = 0; i < 10; i++)
{
    var p = document.createElement("p");

    var t = document.createTextNode("asdf");
    p.appendChild(t);

    p.addEventListener("click", function(e){popup(e, i);}, false);

    document.getElementById("someDiv").appendChild(p);
}

let's say, the function is:

function popup(e, id)
{
    //do stuff with the mouse event and get data according to the id
}

so I need the mouse event object.

This current code does make the elements, but every click calls the function with the same id as parameter (10 is being sent as the id, the mouse event works fine).

Any idea is appreciated! Thanks in advance.

War es hilfreich?

Lösung

That's happening because a closure is created that retains the last value of i from the for loop, you need to change this line:

p.addEventListener("click", function(e){popup(e, i);}, false);

To fix this, first declare a new function:

function createfunc(i) {
    return function(e) {popup(e, i); }
}

Then change that line to:

p.addEventListener("click", createfunc(i), false);

Check this question for more information about this technique.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top