Having to do some UI work this week... not something I am used to! Basically I have an array of objects (in this case simplified as integers) and need to loop through them to find a matching element on the page and attach an event handler with the data from that part of the array. I think this is a scoping issue - then I played around assigning _local = this; it always seemed that the last item in the loop was attached to the handler (i.e. it would always say the last value has been clicked for all the buttons)
$(document).ready(function () {
var filters = [0,1,2,3];
// Works as expected
// When button 0 is clicked log message is "btn0 clicked!"
// When button 1 is clicked log message is "btn1 clicked!"
// Etc
$('#btn0').on('click', function () {
console.log("bt0 clicked");
} );
$('#btn1').on('click', function () {
console.log("bt1 clicked");
} )
$('#btn2').on('click', function () {
console.log("bt2 clicked");
} )
$('#btn3').on('click', function () {
console.log("bt3 clicked");
} )
// Undefined all over the place
for (var i = 0; i < filters.length; i++) {
$('#btn' + filters[i].toString()).on('click', function () {
console.log("bt" + filters[i].toString() + " clicked");
} );
}
});