1

我的网站在轮播中播放了多个 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.
            }
        }
    }

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

4

1 回答 1

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

于 2015-01-30T09:52:47.373 回答