I am trying to bind a jquery function using a loop. The problem is that the function that gets bound always takes the value of the last item of the list.
Here is a simplified version of the code:
var obj =
{
'.a':'1',
'.b':'2',
'#c':'3'
};
for (var prop in obj)
{
if (obj.hasOwnProperty(prop))
{
alert(prop + '=' + obj[prop]);
$(prop).on('click', function () {
alert(prop + '=' + obj[prop]);
ga('send', 'event', 'link', 'click', obj[prop]);
});
}
}
The ga() function is simulated as follows:
function ga(one, two, three, four, five)
{
alert('simulated GA(): one=' + one + ' two=' + two + ' three=' + three + ' four=' + four + ' five=' + five);
}
The outer alert fires when the javascript is initialized and shows the values of all of the object properties as expected. But when the DOM element is clicked on, the inner alert and the ga() function shows the value of the last property #c, no matter which DOM element is clicked.
The purpose of this code is to assign various calls to ga() to different DOM objects identified by the properties which are selectors.
I am thinking there is something simple and stupid that I am missing here.