0

I am having a problem with JQuery at the moment where I am trying to parse a integer variable in a for loop in a eq() function. The problem I am having is when I try append the class ".episode-l" (needs to be a class as there are multiple of these and are displayed with a getjson) in a certain location with the eq() function but it wont display with a variable, I need it as a variable as i need to increment it each loop. There are other posts like this but I have looked at them and none of them work. Here is the code:

for( var i = 0; i < filmnamevar.length; i++)
{           
    $.getJSON('http://api.themoviedb.org/3/search/movie?query='+ filmnamevar[i] +'&api_key=81c50c197b83129dd4fc387ca6c8c323',function(dataa){

        $('.episode-l').eq(i).append('<div class="rating">'+ dataa.results['0'].vote_average +'</div>');
        console.log(i);
    });
} 

1 Answers1

0

It is a common problem associated with the usage of a closure in a loop.

Assuming filimnamevar is a array, since you are using jQuery you can use $.each()(instead of using an IIFE function as given in the below links but the principle behind the problem is the same)

$.each(filmnamevar, function (i, val) {
    $.getJSON('http://api.themoviedb.org/3/search/movie?query=' + val + '&api_key=81c50c197b83129dd4fc387ca6c8c323', function (dataa) {

        $('.episode-l').eq(i).append('<div class="rating">' + dataa.results['0'].vote_average + '</div>');
        console.log(i);
    });
})

Read

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • I would have been confused forever at this one, so thank you so much. –  Feb 19 '14 at 23:35