问题
Follow this tutorial, I have been trying to integrate the YouTube API into my website. Specifically, when a button is pressed I want to play a video hosted on YouTube in fullscreen mode. Unfortunately, I can't even get the code given in that tutorial to work.
I'm using Slim for markup so I added an empty div with the ID of player as the tutorial suggests
.body
.player
I then added this javascript at the end of my markup
$(document).ready(
function() {
loadYoutubeAPI();
});
Which should start the chain of calling these functions
function loadYoutubeAPI() {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
However, the chain of calls stops before onPlayerReady fires and I can't figure out why.
回答1:
From what I can see, it seems as though your issue may be in the player div seems to be of the class player and from what I can see in the tutorial, its looking for an div with player id. so something like the following may work:
.body
#player
I am not 100% familiar with Slim so you may need to mark this up differently.
来源:https://stackoverflow.com/questions/40163343/youtube-api-onplayerready-is-never-getting-called