youtube-“yt”未定义

w1jd8yoj  于 2021-09-23  发布在  Java
关注(0)|答案(1)|浏览(299)

我试图通过以下代码使用youtube播放器:

var tag = document.createElement('script');

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

            new window.YT.Player("video", {
                height: '432',
                width: '768',
                videoId: link,
                playerVars: {
                    'playsinline': 1, 'autoplay': 1
                },
                events: {
                    'onReady': onPlayerReady,
                    'onStateChange': onPlayerStateChange
                }
            });
        }

但是,不断出现错误:
未捕获类型错误:无法读取未定义的属性“player”

abithluo

abithluo1#

从代码中删除以下行:

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


添加函数 onPlayerReady()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('player', {
          height: '390',
          width: '640',
          videoId: '668nUCeBHyY',
          playerVars: {
            'playsinline': 1
          },
        });
      }
<div id="player"></div>

相关问题