2012-10-29 107 views
3

我有我的網站的YouTube視頻列表,這是每個項目的樣子:的Javascript的YouTube API - 載入播放器

<div class="video_item" id="<YouTubeVideoID>"> 
    // video thumbnail and information 
</div> 

如果用戶點擊這些視頻項目,面板跌幅之一下來,應該加載API,並顯示視頻播放器,一旦面板已經完成了它的滑動操作:

$(document).ready(function(e) { 
    $('.video_item').live('click', function() { 
     var vid_id = $(this).attr('id'); 
     if (vid_id) { 
      $("html").animate({ scrollTop: $('#main').offset().top-20 }, 1000, function() { 
       setTimeout(function() { 
        $('.video_drop_panel_wrap').slideDown('slow', function() { 

         var tag = document.createElement('script'); 
         tag.src = "http://www.youtube.com/iframe_api"; 
         var firstScriptTag = document.getElementsByTagName('script')[0]; 
         firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); 

         var player; 
         function onYouTubeIframeAPIReady() { 
          player = new YT.Player('youtube_player', { 
          height: '371', 
          width: '570', 
          videoId: vid_id, 
          events: { 
           'onReady': onPlayerReady 
          } 
          }); 
         } 

         function onPlayerReady(event) { 
          event.target.playVideo(); 
         } 
        }); 
       },1000); 
      }); 
     } 
    }); 
}); 

的問題是,它不會顯示的球員,我沒有收到我的JS開發人員控制檯中有任何錯誤我已經測試了API和播放器,沒有使用所有的滑動面板,並且工作 - 只是不在我想要的位置。我不確定這是否是DOM問題或其他問題。如果有人能夠發現我做錯了什麼,我會感激一巴掌...哦,並告訴我什麼是錯的。

回答

3

發生此錯誤是因爲您的onYouTubeIframeAPIReady()在全局範圍內不存在,它只存在於$('.video_drop_panel_wrap').slideDown('slow', function() {...})之內。 api的延遲加載相當於從範圍的角度將它放在<script>標記中,以便它搜索全局函數。

您可以重構您的代碼,以便在onYouTubeIframeAPIReady()觸發時指向您希望加載的視頻的相關信息。

大致一旦加載API你最終

<script> 
     //Youtube api stuff 
     (function(){ 
      //Do Stuff 
      onYouTubeIframeAPIReady(); 
     })(); 
</script> 
<script> 
     $(document).ready(function(){'Your Stuff Here'}) 
</script> 

所以當API準備調用時它不知道它原來是因爲它從它自己的,獨立的功能來源於上下文。

的粗溶液可以是因爲已經不使用var語句變量將在全球範圍內被創建,如果它是無法定義從下方var player行代碼改變到

onYouTubeIframeAPIReady = function(){ 
    player = new YT.Player('youtube_player', { 
    height: '371', 
    width: '570', 
    videoId: vid_id, 
    events: { 
     'onReady': onPlayerReady 
    } 
    }); 
} 

在範圍鏈中找到同名變量。 onPlayerReady不需要相同的處理,因爲它在創建onYouTubeIframAPIReady時存在(本地範圍)。

+0

我認爲API是被稱爲在行'var標記=使用document.createElement( '腳本');'它調用了'onYouTubeIframeAPIReady() '功能。當然,這是在全球範圍內,因爲函數和API創建者都在'document.ready'中? – ShadowStorm

+0

與其他函數一樣,'$(document).ready(function(){...})內部定義的變量只存在於函數中。 – Crazometer

+0

玩了一下後,我現在明白你在向我解釋什麼。 TBH,我不確定這種API方法是否適合我的情況。我剛剛使用了SWF版本,效果更好。我感謝您的耐心,並會接受答案,因爲它是正確的。 – ShadowStorm

相關問題