Youtube iframe api" getPlayerState"功能未定义

时间:2015-01-29 22:18:36

标签: youtube-api youtube-javascript-api youtube-iframe-api

我的网站在转盘中播放了多个YouTube视频。当用户点击youtube视频时,我想停止旋转木马的自动滚动。这是我写的代码,它让我"玩家[player_id] .getPlayerState()不是函数" 错误。

此外,youtube库正在从我的网站加载第三方javascript。

players = {};

    window.onYouTubeIframeAPIReady = function(){
        $('.youtube-video iframe').each(function() {
            players[$(this).attr('id')] = new YT.Player($(this).attr('id'), {
                events: {
                    'onStateChange': onPlayerStateChange($(this).attr('id'))
                }
            });
        });

    }

    function onPlayerStateChange(player_id){
        return function(event) {
            if(players[player_id].getPlayerState() == 3 ||players[player_id].getPlayerState() == 1) {
                //stop the auto scrolling
            }

            if(players[player_id].getPlayerState() == 0 || players[player_id].getPlayerState() == 2) {
                //start auto scrolling.
            }
        }
    }

如果您能在我的代码中找到问题,请与我们联系。提前谢谢!

1 个答案:

答案 0 :(得分:2)

您忘记了一些示例参数,例如videoId: $(this).attr('id')events 没有放在好地方。

我发给你正确的代码:

<强> HTML

  <div class="youtube-video" id="O1RHkPGb31Q"></div>
  <div class="youtube-video" id="VjRb3RjqncQ"></div>

<强>使用Javascript:

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

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

players = {};
window.onYouTubeIframeAPIReady = function(){
        $('.youtube-video').each(
  function() {
    players[$(this).attr('id')] = new YT.Player($(this).attr('id'), 
    { 
      videoId: $(this).attr('id'), 
      events: { 'onStateChange': onPlayerStateChange($(this).attr('id')) }
    });
  });
};

    function onPlayerStateChange(player_id){
        return function(event) {
            if(players[player_id].getPlayerState() == 3 || players[player_id].getPlayerState() == 1) {
                //stop the auto scrolling
                console.log("stop scolling video" + player_id);
            }

            if(players[player_id].getPlayerState() == 0 || players[player_id].getPlayerState() == 2) {
                //start auto scrolling.
              console.log("start scolling video" + player_id);
            }
        };
    }

现场演示:http://jsbin.com/nisetafoga/1/edit?html,js,console,output