0

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!

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Isti115
  • 2,418
  • 3
  • 29
  • 35

1 Answers1

2

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.

Community
  • 1
  • 1
Ibrahim Najjar
  • 19,178
  • 4
  • 69
  • 95
  • Thank you for your answer! I wish your first solution would have worked (before the edit), because it was much simpler, but I'm glad that this one does the job. :) PS.: thanks for the more info link. It's really helpful! – Isti115 Nov 01 '13 at 22:08
  • @Isti115 You are welcome, I am not sure my first answer would have worked though. – Ibrahim Najjar Nov 01 '13 at 22:08