内部循环播放多个YouTube播放器实例

时间:2018-04-05 02:55:16

标签: javascript youtube ytplayer

我有以下代码,它有效 - 但我无法弄清楚的部分是如何在onReady事件中获取索引。结果是2,2而不是0,1我希望 - 为什么?

Codepen

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 players = [];
var playerEl = document.querySelectorAll('.ytplayer');

 function onYouTubeIframeAPIReady() {
     for (var i = 0; i < playerEl.length; i++) {

         players[i] = new YT.Player(playerEl[i], {
             events: {
                 'onReady': () => { console.log('index: '+i) } // why doesn't this return 0,1 ??
             }
         });
     }
 }
<iframe class="video ytplayer" width="100%" height="390" type="text/html" src="https://www.youtube.com/embed/ScMzIvxBSi4?controls=0&t=31s&loop=1&playlist=ScMzIvxBSi4&showinfo=0&rel=0&enablejsapi=1" frameborder="0" allowfullscreen></iframe>

<iframe class="video ytplayer" width="100%" height="390" type="text/html" src="https://www.youtube.com/embed/iGpuQ0ioPrM?controls=0&t=31s&loop=1&playlist=iGpuQ0ioPrM&showinfo=0&rel=0&enablejsapi=1" frameborder="0" allowfullscreen></iframe>

1 个答案:

答案 0 :(得分:0)

我设法使用以下代码解决它。我犯的错误是我试图在事件中存储变量。事件是异步的,并且不知道它在一个循环中 - 至少我认为就是它,如果我错了,请纠正我。

Codepen working

 function onYouTubeIframeAPIReady() {
     document.querySelectorAll('.ytplayer').forEach((item) => {
         new YT.Player(item, {
             events: {
                 'onReady': (event) => {
                     event.target.playVideo();
                     event.target.mute();
                 }
             }
         })
     })
}