3

I have the following function:

function createLogos() {
    for (var l=0; l<userList().length; l++) {
        var username = "https://api.twitch.tv/kraken/users/" + userList()[l];
        $.getJSON(username, function(data) {
            $(":eq(l)").append("<img src=" + data.logo +">");
        });
     }
 }

However, the eq(l) is not recognising what l is. Replacing it with a number and it works as to how I wish.

Can anyone see why it might be behaving like this?

Nate Barbettini
  • 51,256
  • 26
  • 134
  • 147
  • 1
    because `l` is a string, not a reference to the variable and using it in a for loop like that after you fix the issue will be another bug. And I doubt you just want ":eq" as your selector – epascarello Apr 05 '16 at 16:27
  • 3
    After the change noted above, reading http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example?rq=1 will probably be relevant. – user2864740 Apr 05 '16 at 16:28
  • Before using :eq, I had this line: $("#theTable .pic").eq(l).append(""); this did not work either, where l is not a string. – smithplusplus Apr 05 '16 at 16:29
  • 1
    that is because of the "infamous for loop" http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – epascarello Apr 05 '16 at 16:31

3 Answers3

1

You can substitute $.map() for for loop, use $.when()

function createLogos() {
    $.when.apply($, $.map(userList(), function(el, index) {
      var username = "https://api.twitch.tv/kraken/users/" + el;
      return $.getJSON(username, function(data) {
        $("#theTable .pic").eq(index).append("<img src=" + data.logo +">");
      })
    }))
 }
guest271314
  • 1
  • 15
  • 104
  • 177
0

In your code you are looking for index l not the current index of the loop. Now id you were do do it by referencing the variable you will have a different problem since l will be evaluated when the code is hit so it will be the wrong value.

So what you need to be is reference the element before the JSON call

function createLogos() {
    for (var l=0; l<userList().length; l++){
        var username = "https://api.twitch.tv/kraken/users/" + userList()[l],
            pic = $("#theTable .pic").eq(l);
        $.getJSON(username, function(data){
            pic.append("<img src=" + data.logo +">");
        });
     }
 }
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

Try to concatenate :eq()
Hope it will work

function createLogos() {
 for (var l=0; l<userList().length; l++){
    var username = "https://api.twitch.tv/kraken/users/" + userList()[l];
    $.getJSON(username, function(data){
       $(":eq("+l+")").append("<img src=" + data.logo +">");
    })
 }
}
Kunal Nigam
  • 326
  • 1
  • 6