I'm making a JS script which takes a 2D array and draws some pictures on the screen. The array contains the data: a unique name, the picture file name, xy coordinates, and z-index. The for loop that takes the elements of the array and draws the pictures on the screen should also give them a function such that when I click on an image the computer knows and does stuff.
The problem is, at each loop I should make the function work on a specific value of the "i" variable (see the code below). I tried some little modifications, but I only managed to see the i disappear after the loop ran, or the i is at the maximum value for every item.
Is there a way to make the functions have a constant value of i, regardless of what the loop does in the meantime with the variable?
This is my very first question on StackOverflow, I'm sorry if I did something wrong. Thanks.
I already tried to "declare" i out of the for loop, this fixed the problem of the variable being deleted after the loop but now every function works for the last value of i. Then I tried to store the value of the "i-s" in a separate array, but this only made a lot of confusion in the code without fixing the problem.
var img = [];
var g = [// some stuff............................
["bcc", "BELL", xbemb + 350, ybem + 542, 30]];
for (i = 0; i < g.length; i++) {
//omissis
//here it creates the function which should have a different
//i value for each element but does not
img[g[i][0]].onmousedown = function() { topo(g[i][0]); };
//omissis
}
I click on any element but it returns "bcc" (the name of the last element in the array)