javascript / youtube api - variable YT is not defined

后端 未结 2 1336
醉话见心
醉话见心 2020-12-15 12:28

I\'m creating a youtube player embed via the YT api but I keep getting an alert that the variable YT is not defined. I can see that the script for the youtube API is getting

2条回答
  •  天涯浪人
    2020-12-15 13:22

    This is the method I like best. Uses jQuery FYI.

    var player = {
        playVideo: function(container, videoId) {
            if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') {
                window.onYouTubePlayerAPIReady = function() {
                    player.loadPlayer(container, videoId);
                };
                $.getScript('//www.youtube.com/player_api');
            } else {
                player.loadPlayer(container, videoId);
            }
        },
        loadPlayer: function(container, videoId) {
            window.myPlayer = new YT.Player(container, {
                playerVars: {
                    modestbranding: 1,
                    rel: 0,
                    showinfo: 0,
                    autoplay: 1
                },
                height: 200,
                width: 200,
                videoId: videoId,
                events: {
                    'onStateChange': onPlayerStateChange
                }
            });
        }
    };
    
    var containerId = 'ytplayer';
    var videoId = 'abc123';
    player.playVideo(containerId, videoId);
    

提交回复
热议问题