本文介绍了有时YouTube API尚未准备就绪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用其API包含youtube vid.但是,有时(确实是随机的.多数情况下,它是可行的)单击播放按钮时出现错误:
I'm trying to include a youtube vid using their API. However, sometimes (really random. Most times it works) I get an error when I click my play button:
Cannot read property 'playVideo' of undefined
这就是我包含API的方式:
This is how I included the API:
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('video-intro', {
width: 100,
height: 100,
videoId: '<id>',
playerVars: {
color: 'white',
controls: 0,
showinfo: 0
}
});
}
$(document).ready(function() {
$('#play-intro').click(function() {
player.playVideo();
$('#video-intro').addClass('showvid');
});
});
#video-intro {
display: none;
&.showvid {
display: block;
}
}
<head>
<script src="https://www.youtube.com/iframe_api"></script>
</head>
<body>
<div id="video-intro"></div>
<a id="play-intro">Play</a>
</body>
推荐答案
不幸的是,它在SO Snippet中不起作用.尝试先显示该元素(您的CSS无法正常工作),然后调用player.playVideo()
,否则将显示错误,如您的问题所示.
Unfortunately it is not working in SO Snippet. Try to show the element first (Your CSS is not working) then call player.playVideo()
otherwise it will give error as shown in your question.
使用下面的CSS展示您的iframe,
Use the below CSS to show your Iframe,
#video-intro {
display: none;
}
#video-intro.showvid {
display: block !important;
}
HTML:
<div id="video-intro"></div>
<a id="play-intro">Play</a>
<script src="https://www.youtube.com/iframe_api"></script>
<script>
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('video-intro', {
width: 100,
height: 100,
videoId: 'TZbUi0FP5AM', //T7Kmc7T-pjY (old, short)
playerVars: {
color: 'white',
controls: 0,
showinfo: 0
}
});
}
document.getElementById("play-intro").addEventListener("click", function() {
document.getElementById('video-intro').className = 'showvid';
player.playVideo();
});
</script>
Fiddle
这篇关于有时YouTube API尚未准备就绪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!