0

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.

Jeffrey Simon
  • 918
  • 3
  • 11
  • 25
  • 1
    See [Asynchronous Process inside a javascript for loop](http://stackoverflow.com/questions/11488014/asynchronous-process-inside-a-javascript-for-loop/11488129#11488129) – jfriend00 Sep 07 '15 at 22:18
  • @Nietthedarkabsol - This question is not even close to the same question that was asked in what you marked as a dup. A solution might be found in the answers to that other question, but the question is NOT a dup in any way. That question has nothing to do with this question. Since there are plenty of dups that actually have the same question, it seems you should find an actual dup. – jfriend00 Sep 07 '15 at 22:21
  • @jfriend00 Fair enough. So the one I linked is the more general reference, while the one you guys have linked is an actual duplicate. – Niet the Dark Absol Sep 07 '15 at 23:28
  • My question was not addressed specifically in those other questions, as noted. However, I have been able to adapt the information there to create a solution. Since I cannot paste the new code easily into a comment, I will just say that the solution was to take the contents of the inner if, and replace that with a function call. The new function does the jquery "on' call. And that works. – Jeffrey Simon Sep 07 '15 at 23:29
  • And thanks for both the general and specific answers as they pointed the way. – Jeffrey Simon Sep 07 '15 at 23:33

0 Answers0