onYouTubeIframeAPIReady() 未触发 [英] onYouTubeIframeAPIReady() not firing

查看:39
本文介绍了onYouTubeIframeAPIReady() 未触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经浏览了很多问题和 youtube api 内容,但我一生都无法弄清楚为什么 onYouTubeIframeAPIReady 不起作用.

I've looked through so many questions and the youtube api stuff but for the life of me can't figure out why the onYouTubeIframeAPIReady is not working.

这是我的 iframe:

Here is my iframe:

<iframe id="youtube_vid" width="763" height="430" src="https://www.youtube.com/embed/dlJshzOv2cw?theme=light&amp;showinfo=0&amp;rel=0&amp;enablejsapi=1" frameborder="0" allowfullscreen=""></iframe>

还有我的脚本:

function callYTapi() {

    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    console.log('script loaded');

    function onYouTubeIframeAPIReady() {
        console.log('IframeAPI = Ready');
        var player = new YT.Player('youtube_vid', {
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    }

    function onPlayerReady(event) {
        event.target.playVideo();
    }

    function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PAUSED) {
            console.log("Paused");
        }

        if (event.data == YT.PlayerState.PLAYING) {
            console.log("Playing");
        }

        if (event.data == YT.PlayerState.ENDED) {
            end(); 
        }
    }
}

我得到了已加载脚本的 console.log,但不是 Iframe ready 或其他任何东西.有任何想法吗?谢谢

I get the console.log for the loaded script but not for Iframe ready or anything else. Any ideas? Thanks

推荐答案

回调函数必须在全局范围内.只需将 onYouTubeIframeAPIReadycallYTapi 之外的其他移动.

The callback functions must be in the global scope. Just move onYouTubeIframeAPIReady and the others outside callYTapi.

这篇关于onYouTubeIframeAPIReady() 未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆