我在使用YouTube API中的onError事件时遇到了一些问题。下面是一个带有虚假videoId的脚本,用于创建调用onPlayerError函数的错误。不幸的是,我不明白为什么会调用两次错误函数。我认为可能与回调响应在函数内部有关(也许?),但当videoId正确时,onReady或onStateChange都不会被调用两次。有人能看出任何明显的问题吗?提前谢谢。
顺便说一句:是的,我确实需要回调和回调内的响应。这是我的完整脚本的缩短版本。
顺便说一句:是的,我确实需要回调和回调内的响应。这是我的完整脚本的缩短版本。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- jQuery -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<!-- jQuery / javascript for page -->
<script type='text/javascript'>
//<![CDATA[
//create deferred object
var YTdeferred = $.Deferred();
//attach a function to onYouTubeIframeAPIReady
window.onYouTubeIframeAPIReady = function() {
//resolve when youtube callback is called passing YT as a parameter
YTdeferred.resolve(window.YT);
console.log('Resolved');
};
//embed youtube api script
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
//create player variable
var player;
//create YouTube player
function createyoutubeplayer(nextPageToken)
{
//whenever youtube callback was called = deferred resolved
//your custom function will be executed with YT as an argument
YTdeferred.done(function(YT) {
console.log("create player");
//create new player
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'fff',
playerVars: {
'rel': 0,
'autohide': 1,
'controls': 1,
'showinfo': 0,
'iv_load_policy': 3,
'fs': 0,
'modestbranding': 0,
'playsinline': 1,
'enablejsapi': 1
},
events: {
'onError': onPlayerError,
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
});
}
//when YouTube player is ready
function onPlayerReady(event)
{
//play video
event.target.playVideo();
//unmute sound and set the volume
event.target.unMute();
event.target.setVolume(80);
}
//when YouTube video ends
function onPlayerStateChange(event)
{
//if finished playing
if(event.data === 0)
{
//call next video function
//nextvideo(event);
}
}
function onPlayerError(event)
{
//call next video function
//nextvideo(event);
console.log('Error: ' + event.data);
player.stopVideo();
}
createyoutubeplayer();
//]]>
</script>
</head>
<body>
<!-- video player -->
<div id="player"></div>
</body>
</html>