如何动态更改Youtube Player videoID

Ser*_*der 27 javascript iframe jquery youtube-api

我想使用YT.Player代码,以便我可以检测事件.我有一个带有Youtube视频ID的CSV文件和一个将ID放在一个数组中并希望能够在用户点击图像时动态更改ID的功能.基本上是这样的:

HTML

<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
Run Code Online (Sandbox Code Playgroud)

JavaScript的

// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 3. This function creates an <iframe> (and YouTube player)
//    after the API code downloads.
// NOTE: videoId is taken out and instead is placed as the generated IFRAME src from the postSelection function

var player;
function onYouTubeIframeAPIReady() {
   player = new YT.Player('player', {
      height: '100%',
      width: '100%',
      videoId: '<<CALL TO FUNCTION OR VARIABLE HERE>>',
      events: {
         //'onReady': onPlayerReady,
         'onStateChange': onPlayerStateChange
      }
   });
}
Run Code Online (Sandbox Code Playgroud)

如果您熟悉此代码,那么会发生什么是#playerDIV被IFRAME替换.我可以使用此功能更改IFRAME源:

function postSelection() {
    $("#player").attr("src", _selected.attributes.url); //_selected.attributes.url comes from the CVS file
}
Run Code Online (Sandbox Code Playgroud)

但这是非常错误的,而不是跨浏览器友好.如果我使用标准IFRAME而不是YT Player API,那么一切正常.但我想检测结束,暂停等等所以我必须使用API​​.我的猜测是,这是一个状态问题,并且在创建IFRAME时会出现持久性缺失.

问候.

Gre*_*ter 53

使用js api非常简单.如果要加载新的视频只需要调用player.loadVideoById(videoId); 详细的https://developers.google.com/youtube/iframe_api_reference#loadVideoById

  • 请注意,这是使用iFrame API,因为现在不推荐使用"JavaScript API". (4认同)