问题描述
知道为什么这个脚本不起作用吗?我想要的只是跟踪 onStateChanged
事件,但也从未调用过.
Any idea why this script doesn't work? All I want is to track onStateChanged
event, but that is never called either.
当我用下面的代码打开 html 文档时,我没有错误,youtube 脚本加载得很好,播放器对象不是 undefined
,看起来也不错.
When I open the html document with below code, I have no errors, the youtube script loads just fine, the player object is not undefined
, looks fine too.
$(document).ready(function(){
loadScript();
});
function loadScript() {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
alert(player);
}
var done = false;
function onPlayerStateChange(event) {
alert('state changed');
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 3000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
function onPlayerReady(event) {
event.target.playVideo();
}
我的iframe
:
<iframe id="player width="400" height="300" src="https://www.youtube.com/embed/j0pJekWgeFE" frameborder="0" allowfullscreen></iframe>
见小提琴:https://jsfiddle.net/rg2uy1f8/
推荐答案
我在这里找到了答案:如何获取对现有 YouTube 播放器的引用?
我的解决方案不起作用的原因是我的 iframe
缺少一个属性:enablejsapi="1"
并且我也缺少:?在 YouTube 视频网址中启用 jsapi=1
.
The reason my solution didn't work, was that my iframe
was missing an attribute: enablejsapi="1"
and also I was missing: ?enablejsapi=1
in YouTube video url.
您可以在这里找到可行的解决方案:http://jsfiddle.net/bf7zQ/2/一个>
You may find the working solution here: http://jsfiddle.net/bf7zQ/2/
这篇关于YouTube onPlayerReady 永远不会被触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!