How do I maintain access to the i variable inside my for loop below? I’m trying to learn, not just get the answer, so a bit of explanation would be very helpful. Thank you!
var el,
len = statesPolyStrings.length;
for (var i = 0; i < len; i++) {
el = document.getElementById(statesPolyStrings[i]);
google.maps.event.addDomListener(el, 'mouseover', function() {
$("#"+statesPolyStrings[i]).addClass("highlight");
statesPolyObjects[i].setOptions({ strokeWeight: '2' });
});
}
All of your callbacks share the same
ivariable.When the event handler actually runs,
iis after the end of the array.You need to wrap the loop body in a self-invoking function that takes
ias a parameter.This way, each iteration will get its own, unchanging,
ivariable.For example: