2012-10-29 109 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

相关问题