smithplusplus
smithplusplus

Reputation: 53

.eq() argument not working in loop

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?

Upvotes: 3

Views: 95

Answers (3)

Kunal Nigam
Kunal Nigam

Reputation: 326

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 +">");
    })
 }
}

Upvotes: 0

guest271314
guest271314

Reputation: 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 +">");
      })
    }))
 }

Upvotes: 1

epascarello
epascarello

Reputation: 207527

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 +">");
        });
     }
 }

Upvotes: 0

Related Questions