问题描述
我要做的是获取当前正在播放的youtube视频的当前视频ID,并将其显示在div中.
The thing I am trying to do is to get the current video Id of the youtube videos that are currently playing and display it in a div.
这是我的YT iframe
API代码(例如在Google开发者网站上的基本示例中):
This is my YT iframe
API code (like in the basic example on the google dev site):
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: currentVideoId,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange,
'onError': onError,
},
});
}
如您所见,VideoId(它将播放的第一个视频)由一个名为"currentVideoId"的变量设置,该变量的设置如下:
as you can see, the VideoId (the first video it will play) is set by a variable called "currentVideoId", which was set before like this:
var currentVideoId = '9z4Kft47kBM'
我想在div中显示当前ID
I want to display the current ID in a div
<div id="currentVideoDiv"></div>
为此,我使用了以下代码:
To do this i used this code:
$('#currentVideoDiv').html('Currently Playing:' + currentVideoId);
到目前为止,它可以正确显示我的第一个videoID.
so far so good, it shows my first videoID correctly.
现在,在第一个视频结束后,onStateChange事件将调用此函数:
Now after the first video has ended, the onStateChange event will call this function:
function onPlayerStateChange(event) {
if(event.data === 0) {
swapVideo();
}
}
"swapVideo"函数将调用函数getId();
The "swapVideo" function will call the function getId();
function swapVideo() {
player.stopVideo();
player.loadVideoById(getId());
}
getId()函数将从xml文件中获取随机的videoID,不必为此担心.
The getId() function will get a random videoID from an xml file, don´t worry about that in detail.
function getId() {
return videos[Math.floor(Math.random() * videos.length)];
}
因此现在正在播放具有新videoId的新视频,但是currentVideoDiv中的值仍然相同,因为没有任何更改.
So now a new video with a new videoId is playing, but the value in the currentVideoDiv is still the same since nothing did change it.
问题是,如何获取由getId函数随机设置的新的当前ID,并将其显示在currentVideoDiv中?
The question is, how can i get the new current id, which was set randomly by the getId function and display it in the currentVideoDiv?
推荐答案
这是基于您在loadVideoById
function swapVideo() {
var currentVideoId = getId();
player.stopVideo();
player.loadVideoById(currentVideoId);
$('#currentVideoDiv').html('Currently Playing:' + currentVideoId);
}
这篇关于获取返回随机值的函数的当前值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!