我正在使用Youtube API,并且有几个Div作为缩略图。当单击一个缩略图(div)时,应播放相应的Youtube视频。我正在使用iframe元素进行视频播放,网页仅由HTML、CSS和JavaScript组成。如果我不使用按钮(具有onclick的缩略图/ div),而是使用带有Youtube API JavaScript代码的空白页面,它将起作用。但是,当我尝试将所有内容包装在函数调用中(从div的onclick),什么都不会发生,但是我会收到以下错误消息。
"Refused to execute script from 'https://www.youtube.com/embed/HVldRjNb4BE' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled."
这是我的代码:
HTML:
<div id="player"></div>
JavaScript:
// 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: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
//setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
这段代码是从https://developers.google.com/youtube/iframe_api_reference复制的。
如果这是文档中唯一的内容,当页面加载时会有一个播放器,视频也已准备好播放。因此,为了澄清我的问题,我该如何做才能让用户点击其中一个按钮(div)时,Youtube播放器显示并播放视频呢?