问题
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.
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,
},
});
}
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'
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);
so far so good, it shows my first videoID correctly.
Now after the first video has ended, the onStateChange event will call this function:
function onPlayerStateChange(event) {
if(event.data === 0) {
swapVideo();
}
}
The "swapVideo" function will call the function getId();
function swapVideo() {
player.stopVideo();
player.loadVideoById(getId());
}
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)];
}
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.
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?
回答1:
This is based on the assumption that you update the display id after loadVideoById
function swapVideo() {
var currentVideoId = getId();
player.stopVideo();
player.loadVideoById(currentVideoId);
$('#currentVideoDiv').html('Currently Playing:' + currentVideoId);
}
来源:https://stackoverflow.com/questions/20274897/get-the-current-value-of-a-function-which-returns-random-values