我正在使用SWFObject将YouTube视频嵌入到我们的网站中.一页中有许多指向视频的链接,每个链接都会清除包装div,然后使用以下代码将新的嵌入内容嵌入其中:
$('a.video-link').each(function () {
$(this).on('click', function(e) {
e.preventDefault();
if ($('#video-wrap').has('object').length == 0) {
var params = { allowScriptAccess: 'always', allowFullScreen: 'true' };
var atts = { id: 'ytapiplayer' };
swfobject.embedSWF($(this).attr('href'), 'ytapiplayer', '1000', '562', '8', null, null, params, atts);
$('#video-wrap').show();
} else {
$('#video-wrap').find('object').remove();
$(this).trigger('click');
}
});
});
这些是我用于每个嵌入的Youtube链接:
http://www.youtube.com/v/{Youtube ID}?hl=en_US&rel=0&hd=1&border=0&version=3&fs=1&autoplay=1&autohide=1&enablejsapi=1&playerapiid=ytapiplayer
然后,这是onYouTubePlayerReady()事件处理程序:
function onYouTubePlayerReady(id) {
console.log('youtube player is ready.');
var ytplayer = document.getElementById('ytapiplayer');
ytplayer.addEventListener('onStateChange', 'onYouTubePlayerStateChange');
ytplayer.addEventListener('onError', 'onYouTubePlayerError');
}
所有视频加载正常,但是onYouTubePlayerReady从未被点击!
请帮我解决这个问题.最终目标是使Youtube API正常运行.
谢谢.
编辑:我尝试使用代码,确保所有名称正确,分成不同的脚本标签和/或.js文件,将其加载到document.ready()内部的开头,但onYouTubePlayerReady不会触发.你怎么看?
解决方法:
这是工作代码:
在每个视频链接上执行SWFObject:
$('a.video-link').on('click', function(e) {
e.preventDefault();
// SWFObjects loads a video object into div with ID ytapiplayer.
// If the wrapper div already contains a video we need to remove it first:
if ($('#video-wrap').has('object').length == 0) {
var params = { allowScriptAccess: 'always', allowFullScreen: 'true' };
var atts = { id: 'ytapiplayer' };
swfobject.embedSWF($(this).attr('href'), 'ytapiplayer', '1000', '562', '8', null, null, params, atts);
$('#video-wrap').show();
} else {
$('#video-wrap').find('object').remove();
$(this).trigger('click');
}
});
具有API值的YouTube链接:
http://www.youtube.com/v/' + data.YoutubeLink + '?hl=en_US&rel=0&hd=1&border=0&version=3&fs=1&autoplay=1&autohide=1&enablejsapi=1&playerapiid=ytapiplayer
我将SWFObject事件处理程序将此代码放在一个单独的.js文件中,该文件在执行SWFObject的代码之前加载.我不知道是否有必要,但是无论如何它都在工作:
function onYouTubePlayerReady(id) {
// We need the actual DOM element for this, if we want to use more advanced API.
// This is because addEventListener activates the API.
var ytplayer = $('#ytapiplayer').get(0);
ytplayer.addEventListener('onStateChange', 'onYouTubePlayerStateChange'); // onYouTubePlayerStateChange(newState)
ytplayer.addEventListener('onError', 'onYouTubePlayerError'); // onYouTubePlayerError(errorCode)
}