无法解雇" loadVideoByUrl(' ...')" Youtube的iframe-API - 未定义

时间:2016-01-16 19:02:15

标签: javascript youtube-iframe-api

似乎我错过了一些明显的东西,但我无法得到

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('player1');
    // here everything is fine and I can see the 
    // function as part of player
    console.log(player);
    // but here it says "player.loadVideoByUrl()" undefined
    player.loadVideoByUrl("https://youtu.be/bHQqvYy5KYo");
    player.playVideo();
}

上班。有什么想法吗?

提前致谢!

1 个答案:

答案 0 :(得分:2)

我认为在您调用player函数时loadVideoByUrl未初始化。在文档中,他们使用

events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }

玩家的事件。看起来玩家对象是异步构造的。因此,如果您使用这些事件,代码将如下所示:

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('player1', {
      events: {
        'onReady': onPlayerReady
      }
    });
}

function onPlayerReady(){
     player.loadVideoByUrl("https://youtu.be/bHQqvYy5KYo");
     player.playVideo();
}