javascript - Youtube iframe API 无法按预期工作

标签 javascript youtube youtube-api

在我的一个模态中,我想显示一段 YouTube 视频。哪一个(哪个 ID)取决于使用哪个按钮打开模型。

<button class='yt-play' data-yt='xxxxxx'>Play video</button>

在我的 javascript 文件中,我使用 YT 播放器 api 生成 iframe;我关注了Getting started on google developers .

所以在模态中我添加了 <div id='player'></div>这是我包含的 javascript:

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

function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    videoId: '5ulO97zuVF0', //- just a temporary id
  });
}

// on document ready do some jQuery things, 
// like adding an event handler to the button. 
$(document).ready(function (){

   $('.yt-play').click(function(ev){
        ev.preventDefault();
        var videoid = $(this).data('yt');

        player.loadVideoById(videoid);
        $('#yt-player').modal('show');
        player.playVideo();

    });

});

yt-play 上的点击处理程序应通过player.loadVideoById() 加载视频,如所述 here in the documentation

但不知怎的,我收到了一个 javascript 错误:TypeError: player.loadVideoById is not a function

如果我将玩家对象转储到控制台中,我会得到一个不错的玩家对象;其中包含 loadVideoById 函数等许多函数。至少看起来是这样的:

console screenshot

新视频未加载的原因是什么?

最佳答案

可能是因为“loadVideoById”尚不可用。

您必须使用事件对象构造 YT.Player 对象,并包含“onReady”事件回调。

然后在“onReady”回调函数中绑定(bind)按钮单击事件。

function onPlayerReady() {
    $('.yt-play').click(function(ev){
        ev.preventDefault();
        var videoid = $(this).data('yt');

        // player.loadVideoByID is now available as a function
        player.loadVideoById(videoid);

        $('#yt-player').modal('show');
        player.playVideo();
    });
}
player = new YT.Player('player', {
    videoId: '5ulO97zuVF0', //- just a temporary id,
    events:{
        “onReady”: onPlayerReady   
    }
});

有关更多信息,请参阅文档中的事件部分:

https://developers.google.com/youtube/iframe_api_reference#Events

关于javascript - Youtube iframe API 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28633421/

相关文章:

php - 更改 youtube url 以在 php 中嵌入 url

javascript - 按位置识别 HTML 类并将其添加到 masonry 项目

javascript - 如何使用 document.querySelectorAll 选择除 anchor (另一个元素内的 anchor )以外的所有标签?

javascript - 更改网站中所有页面的样式

ios - 如何在 UIWebView 中自动播放 YouTube 视频

ffmpeg - YouTube live 说没有收到数据

c# - 如何使用 c# 控制 youtube flash 播放器?

javascript - 为什么以及何时 for 循环忽略 html 集合中的某些项目

php - 如何在 php 中使用 youtube api 为播放列表设置缩略图?

security - YouTube API v3 - 我真的需要使用 OAuth 进行基本的读取操作吗?