Reputation: 8277
I have a loop which im trying to make onclicks with their own ID number but it keeps updating to the last number in the loop - im wondering how i can stop it over writing the variable so they keep their own number?
This is what i have:
count = 0;
for(i in my_array){
if(my_array[i][2])){ //if the data value is true
document.getElementById('div_id_'+count).onclick = function()
{
alert(i);
};
count++;
}
}
Thing is alert(i) always shows the last value of my_array... so im wondering how i can stop it over writing each time so each div can parse their own value?
Upvotes: 0
Views: 76
Reputation: 5684
count = 0;
my_array.forEach(function(i) {
if(my_array[i][2])){ //if the data value is true
document.getElementById('div_id_'+count).onclick = function()
{
alert(i);
};
count++;
}
});
if my_array is Object instead of Array
count = 0;
Object.keys(my_array).forEach(function(i) {
if(my_array[i][2])){ //if the data value is true
document.getElementById('div_id_'+count).onclick = function()
{
alert(i);
};
count++;
}
});
Upvotes: 1
Reputation: 11993
You are running into an issue with Closure. It is a tricky topic. Check out this url: http://code.google.com/apis/ajax/playground/#closure_for_events
Basically the i
value is evaluated when you click the element; not when you assign the event so at that point i
is set to the last value in the loop. You need to create a separate function to bind to the click event that takes the i
parameter. An example:
function HandleClick(i){
return function() { alert(i); };
}
count = 0;
for(i in my_array){
if(my_array[i][2])){ //if the data value is true
document.getElementById('div_id_'+count).onclick = HandleClick(i);
count++;
}
}
Now the HandleClick
function is creating its own closure for the i
, and it will be set to the value passed in from the loop.
Upvotes: 3
Reputation: 2243
Stash the value in the element:
var count = 0;
for (var i in my_array)
{
if (my_array[i][2])) //if the data value is true
{
var el = document.getElementById('div_id_'+count);
el.setAttribute("my_value", i);
el.onclick = function()
{
alert(this.getAttribute("my_value"));
};
count++;
}
}
Upvotes: 1