Pergunta

I'm having this problem with the following code: http://jsfiddle.net/double0seven/z3Yr4/

var feedurl = "https://itunes.apple.com/nl/rss/topsongs/limit=25/xml";
var j, i, x;
$.getJSON("http://ajax.googleapis.com/ajax/services/feed/load?q=" + feedurl + "&v=1.0&num=-1&callback=?", function(data) {
    for (j = 0; j < 21; j += 1) {
        qt = j + ". " + data.responseData.feed.entries[j].title.replace('#', '');
        console.log(qt);
        li = $("<li/>").html(qt).appendTo('#ul1');
        $.getJSON("http://gdata.youtube.com/feeds/api/videos?q=" + qt + "&v=2&start-index=1&max-results=1&orderby=relevance&format=5&alt=jsonc&callback=?", (function(el) {
            return function(videoFeed) {
                for (i = 0; i < videoFeed.data.items.length; i += 1) {
                    entry = videoFeed.data.items[i];
                    track = qt;
                    var liid = liid += 1;
                    el.empty();
                    el.addClass("item");
                    el.attr('id', i);
                    el.attr('ytid', entry.id);
                    el.attr('titel', entry.title);
                    newdiv = $(document.createElement("div"));
                    newdiv.addClass("mod");
                    newdiv.append("<h3>" + qt + "<br></h3>");
                    el.append(newdiv);
                }
            };
        }(li)));
    }
})

Here's what it needs to do:

  1. get titles from RSS feed (works)
  2. put them (until max of 20) in an unordered list - note ordered by nr. (works)
  3. search for each title a nice video on youtube api (works)
  4. put some info into the created li (works)(ytid is o.k. and so is the title)
  5. the it needs to get the variable qt from the outer/mother function to go with it. However - it always gets the LAST filled qt variable in the row...

can't figure out why, need to have something to do with another closure I think. but not sure. I searched all over the internet but no clue.

Thanks for your help.

Foi útil?

Solução

What's happening is that the qt-reference is being updated each iteration in your outer loop, and when the first Ajax-response to the Youtube API is completed, the outer loop has already reached the end.

You will have to store each qt-reference with each inner Ajax-request so the requests will update the relevant LI.

Easiest way to do this is to create a function that returns a function that uses a parameter of the outer function:

var renderLi = function (qt, el) {
    return function(videoFeed) {
        ...
    };
};

...

$.getJSON("http://gdata.youtube.com/feeds/api/videos?q=" + qt + "&v=2&start-index=1&max-results=1&orderby=relevance&format=5&alt=jsonc&callback=?", renderLi(qt, li));

http://jsfiddle.net/z3Yr4/24/

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top