浏览器刷新时不会显示Youtube API iframe

时间:2017-07-06 13:04:58

标签: javascript youtube-api

以下脚本运行正常,但是以非常随机的顺序,当我刷新浏览器时,iframe youtube生成的视频没有显示(有时它们会显示,它非常随机)。 iframe不会生成,并且标记只有空div,最终将被iframe替换。

我正在使用脚本标记加载youtube API:

<script src="https://www.youtube.com/iframe_api"></script>

当视频没有显示时,我也没有在控制台中出现任何错误。

$(document).ready(function(){

    window.onYouTubePlayerAPIReady = function() {
        var players = [], vids=[], player0, player1, player2;

        for (var i = 0; i < document.querySelectorAll(".video-thumb__single").length; i++) {
            players.push(document.querySelectorAll(".video-thumb__single")[i].dataset.videoId);
        }

        player0 = new YT.Player('player0', {
          height: '200',
          width: '400',
          videoId: players[0],
          events: {
            'onStateChange': onPlayerStateChange
          }
        });
        vids.push(player0);

        player1 = new YT.Player('player1', {
          height: '200',
          width: '400',
          videoId: players[1],
          events: {
            'onStateChange': onPlayerStateChange
          }
        });
        vids.push(player1);

        player2 = new YT.Player('player2', {
          height: '200',
          width: '400',
          videoId: players[2],
          events: {
            'onStateChange': onPlayerStateChange
          }
        });
        vids.push(player2);

        function onPlayerStateChange(event) {
            if (event.data == YT.PlayerState.PLAYING) {
              stopVideo(event.target.a.id);
            }
        }

        function stopVideo(player_id) {
            console.log(vids);
            for (var i = 0; i < vids.length; i++) {
              if (player_id != vids[i].a.id)
                vids[i].stopVideo();
            }
        }

    }

});

1 个答案:

答案 0 :(得分:0)

我最终做了以下事情:

    window.onYouTubeIframeAPIReady = function() {
        player0 = new YT.Player('player0', {
            height: '390',
            width: '640',
            videoId: ids[0],
            events: {
                'onStateChange': onPlayerStateChange
            }
        });

        player1 = new YT.Player('player1', {
            height: '390',
            width: '640',
            videoId: ids[1],
            events: {
                'onStateChange': onPlayerStateChange
            }
        });

        player2 = new YT.Player('player2', {
            height: '390',
            width: '640',
            videoId: ids[2],
            events: {
                'onStateChange': onPlayerStateChange
            }
        });
    }

必须将“onYouTubeIframeAPIReady”附加到窗口对象。 API表示该函数必须在全局范围内被触发。这解决了我的问题,但我仍然不明白它与以前有什么不同。