我在YouTube api中的onError事件遇到了一些问题。下面是一个带有假videoId的脚本,用于创建一个调用函数onPlayerError的错误。不幸的是我无法理解为什么错误函数被调用两次。我认为这可能与函数内部的回调响应(可能是?)有关,但是当videoId正确时,onReady或onStateChange都不会被调用两次。谁能看到任何明显的问题?提前谢谢。
BTW:是的,我确实需要回调和回调中的响应。这是我完整脚本的缩短版本。
<!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>
答案 0 :(得分:0)
我认为你错过了听众。
player.addEventListener(event:String, listener:String):Void
https://developers.google.com/youtube/iframe_api_reference#addEventListener