3

Part of a website I am working on is a video page. I am pulling the videos from a YouTube account by accessing the YouTube Data API. Grabbing the videos in no particular order and not sorted works fine, but when I try to sort them into categories, I start running into trouble. Let's say there are three categories, Fruit, Vegetable, Pets. Instead of grabbing all the videos at once, I want to grab all the videos tagged with Fruit, append them to a <ul id="Fruit">. Then request all videos tagged with Vegetable, etc.

When starting out, I had the browser alert when it had finished getting the request and then appending the appropriate list. After I took out the alert, it still worked, but not the way I expected. Either the loop is advancing too quickly, or not advancing at all, but I can't seem to spot the mistake. What ends up happening is that all the videos get put into one list, <ul id="Vegetable">.

Please note: I am using a plugin called jGFeed which wraps the jQuery getJSON function, so I believe you can treat it as such.

 var videoCategories = ['Fruit', 'Vegetable', 'Pets'];

 for (var i = 0; i < videoCategories.length; i++) {
    var thisCategory = videoCategories[i];
    $.jGFeed('http://gdata.youtube.com/feeds/api/users/username/uploads?category='+thisCategory,
    //Do something with the returned data
    function(feeds) {
       // Check for errors
       if(!feeds) {
         return false;
       } else {
         for(var j=0; j < feeds.entries.length(); j++) {
            var entry = feeds.entries[i];
            var videoUrl = entry.link;
            $('ul#'+thisCategory).append('<li><a href="#" id="'+videoUrl+'">'+entry.title+'</a></li>');
         }
       });
 }
4

1 回答 1

3

问题是,您正在使用“thisCategory”变量来设置类别名称。问题是,在您等待服务器响应时,此变量的值是否发生变化。

您可以尝试将整个脚本放在一个函数中:

var videoCategories = ['Fruit', 'Vegetable', 'Pets'];

for (var i = 0; i < videoCategories.length; i++) {
    getCategory(videoCategories[i]);
}

function getCategory(thisCategory)
{

    $.jGFeed('http://gdata.youtube.com/feeds/api/users/username/uploads?category='+thisCategory,
    //Do something with the returned data
    function(feeds) {
       // Check for errors
       if(!feeds) {
         return false;
       } else {
         for(var j=0; j < feeds.entries.length(); j++) {
            var entry = feeds.entries[i];
            var videoUrl = entry.link;
            $('ul#'+thisCategory).append('<li><a href="#" id="'+videoUrl+'">'+entry.title+'</a></li>');
         }
       });
 }

我没有测试过这个,所以我不确定它是否有效..

于 2010-02-25T16:37:58.767 回答