0

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).

scon
  • 59
  • 1
  • 6
  • Thanks Taplar - reviewing now – scon Jul 31 '20 at 17:42
  • First thing inside the for-loop you should assign the value of `i` or the value of `link[i]` to a constant. Ex: `const target = link[i];` – Pedro Lima Jul 31 '20 at 17:47
  • Thanks @PedroLima the question mine was supposed to duplicate didn't actually have answers that worked for me. Your answer did. – scon Aug 01 '20 at 03:16

0 Answers0