0

Syntax issue here as the code works fine. I have a for loop and an inline function that must run within it (aQuery callback).

  for (i=1;i <= 5;i++)  
            {
            twitter[i] = $(this).find('twitter' + i).text();
            //$('<div class="twitter[i]"></div>').html(twitter[i]).appendTo('#link_'+i);
            $('.twitter[i]').html(twitter[i]).appendTo('#link_'+i);

            // grab from twitter
            $.getJSON('http://api.twitter.com/1/users/show.json?screen_name='+twitter[i]+'&callback=?', 

            function (data)     
                    {
                          for (j=1;j <= 5; j++)     {
                          twit_count[j] = data['followers_count'].toString();
                          twit_count[j] = add_commas(twit_count[j]);
                          $('#twitter_count'+j).html(twit_count[j]);
                          }
                    }); 
             }

If i=3 I want j to be the same value within the function.

The problem is the j loop runs five times for every i loop.

Passing i as an argument

 function (data, i)

doesn't work, some direction would be highly appreciated.

Thanks,

Max Bye
  • 13
  • 5

2 Answers2

0

Not 100% sure what you want, but if you want to have the callback function just do one set of counters, it shouldn't have a loop in it.

To get the value of j inside the callback to have the same value as i, you have to write a function to return the callback function, and pass the desired value as an argument to the outer function.

$.getJSON(url, ( function(j) { 
      return function(data) { 
          twit_count[j] = data['followers_count'].toString();
          twit_count[j] = add_commas(twit_count[j]);
        $('#twitter_count'+j).html(twit_count[j]);
      }
   } )(i) )

See my answer here for more explanation.

Community
  • 1
  • 1
Mark Reed
  • 91,912
  • 16
  • 138
  • 175
0

Hi guys just to answer my own question.

I wanted a list of Facebook/Twitter followers per page.

var f_page = ["TheHouseofMarley, Another FB ID, Another FB ID, Another FB ID"];

    for(var i=0; i < 1; i++) 
                    {
                        retrieveData(f_page[i]);
                    }

    function retrieveData(teamName) {

    var baseURL = 'http://graph.facebook.com/';
    $.getJSON(baseURL+teamName+"&callback=?", function(data) {
    $('#FBlikes').append(teamname ":" data.likes)
        });
    };

Then in < body >

<span id='FBlikes'></span> 
Max Bye
  • 13
  • 5