2010-01-07 73 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