I've essentially got this code:
var link = ["www.google.com", "www.facebook.com"];
var elementID = ['firstDiv', 'secondDiv'];
for (i=0;i=1;i++){
document.getElementById(elementID[i]).onclick = function () {location.href = link[i];};
}
The click function is successfully assigned. But it seems that the link[i] value isn't evaluated until the element is clicked, by which time its value is 'undefined' (so it doesn't link to a valid address).
Does anyone know the solution to this problem? Do I have to somehow force evaluation of the array at the time of onclick function assignment?
I'm not finding questions about this on stackoverflow, but if answered ones exist, I'd appreciate a link.
Edit I'm not allowed to add an answer because this question has been closed as a duplicate. But Pedro Lima's comment below contained the solution (set a constant to the link value, and then use that constant in the onclick assignment).