Youtube iframe api "getPlayerState"函数未定义


在我的网站上,轮

播中有多个YouTube视频在播放。当用户点击YouTube视频时,我想停止轮播的自动滚动。这是我正在编写的代码,它抛出"players[player_id].getPlayerState()不是函数"错误。

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

玩家 = {};

    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.
            }
        }
    }

如果您可以在我的代码中找到问题,请告诉我。提前感谢!

您忘记了一些示例参数,例如 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

相关内容

  • 没有找到相关文章

最新更新