gpt4 book ai didi

javascript - 选择数组的随机元素来设置 Youtube videoId API

转载 作者:行者123 更新时间:2023-12-02 16:24:29 28 4
gpt4 key购买 nike

我正在尝试设置一个 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>

最佳答案

该函数需要返回选择的视频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,
}
});
}

关于javascript - 选择数组的随机元素来设置 Youtube videoId API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28822315/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com