I'm trying to loop over a simple array, find elements based on the array values, and then add a click event for each element. For some reason (maybe related to the scope?) all the events think they're at the end of the array.
Example HTML:
<!-- "Sectors" -->
<div class="a">a</div>
<div class="b">b</div>
<div class="c">c</div>
Corresponding javascript:
var sectorArray = ["a", "b", "c"];
// Loop over sector letters
for (var s in sectorArray) {
var sector = sectorArray[s];
console.log("Adding click event for sector: " + sector);
$('div.' + sector).on("click", function(e){
console.log("Clicked sector: " + sector);
});
}
When I click on any div, I get the message that I'm on sector "c". Here is a jsfiddle: http://jsfiddle.net/luken/Pd66m/
I was able to fix the problem by making everything inside the for-loop into it's own, separate function... and there are other solutions... But I'd like to figure out why this, above, won't work. Thanks.