2010-01-07 78 views
0

如何将变量赋值给已使用.replace()处理的返回JSON数据,如下所示。 用途:从JSON返回的视频ID构建视频缩略图图像的URL。将变量赋值给jQuery中的操作数据getJSON结果

问题:如何将视频ID(例如mVWhWsgHzKM)分配给变量,以便构建缩略图URL。

$.getJSON(
    'http://gdata.youtube.com/feeds/users/soccerdude1935/favorites?alt=json-in-script&callback=?', 
    function(data){ 
     $.each(data.feed.entry, function(i, item){ 
      // assign variable to the returned JSON data 
      var id = item['id']['$t']; 

      // URL contain video ID is put inside a P tag and assign class ID. 
      $("<p></p>").text(id).addClass('vidId'); 

      $('p.vidId').each(function() { 
       var id = $(this).text(); 
       // removes all other text from URL except for video ID. 
       id = id.replace("http://gdata.youtube.com/feeds/videos/",""); 
       // video ID is assigned to a var. Is this correct? because it is not working as a var. 
       // Note: no errors when running the code. 
       var imgSrc = $(this).text(id); 
      }); 

      // thumbnail URL construction and placement inside a img element's src tag. 
      $(<img />).attr('src', 'http://i2.ytimg.com/vi/'+imgSrc+'/default.jpg'); 
     }); 
    }); 

导致IMG SRC URL看起来像:http://i2.ytimg.com/vi/mVWhWsgHzKM/default.jpg,但是当我运行的代码,它不会使所期望的结果。有什么建议么?

任何想法将不胜感激。谢谢。

回答

1

我剥离了代码以实际获取它进行渲染。我只是用id = video创建了一个div标签,然后将每个缩略图附加到容器中。

使用你的代码,看起来问题在于你的第二条语句。它无法运行,所以它从不为imgSrc分配一个值。现在这可能是因为我没有HTML。

<div id="video"></div> 
    <script> 
     $(document).ready(function() { 
      $.getJSON('http://gdata.youtube.com/feeds/users/soccerdude1935/favorites?alt=json-in-script&callback=?', 
      function(data){ 
       $.each(data.feed.entry, function(i, item){ 
        var id = item['id']['$t']; 

        id = id.replace("http://gdata.youtube.com/feeds/videos/",""); 

        $("#video").append('<div id="'+id+'">'); 
        $("#video").append('<img src="http://i2.ytimg.com/vi/'+id+'/default.jpg">'); 
        $("#video").append('</div>'); 
       }); 
      }); 
     }); 
    </script> 
+0

完美地工作。谢谢! – Steve 2010-01-08 23:44:48