选择数组的随机元素以设置Youtube videoId API

时间:2015-03-03 01:02:49

标签: javascript arrays youtube-javascript-api

我正在尝试设置一个videoId数组,以便能够选择随机加载。我试图将视频数组添加为videoId,但它不起作用。我是一个JS新手,所以我不确定它是什么我应该为此回传。我得到了这个:

<div id="player"></div>

<script>
function rotateYT() {
    var videos = [
        'ZMnjkcvjN-E',
        'RFQfSMbLCWw',
    ];

    var index=Math.floor(Math.random() * videos.length);
}
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');

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

// 3. This function creates an <iframe> (and YouTube player)
//    after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
        height: '300',
        width: '300',
        videoId: videos[index], //where I'm trying to get the random videos
        events: {
            'onReady': onPlayerReady,
        }
    });
}

// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
    event.target.playVideo();
    event.target.mute();
    event.target.setPlaybackQuality('small');
}
</script>

1 个答案:

答案 0 :(得分:2)

该功能需要返回所选的视频ID:

function rotateYT() {
    var videos = [
        'ZMnjkcvjN-E',
        'RFQfSMbLCWw',
    ];

    var index=Math.floor(Math.random() * videos.length);
    return videos[index];
}

然后你需要在onYouTubeIframeAPIReady中调用它:

function onYouTubeIframeAPIReady() {
    var videoID = rotateYT();
    player = new YT.Player('player', {
        height: '300',
        width: '300',
        videoId: videoID,
        events: {
            'onReady': onPlayerReady,
        }
    });
}