javascript - onYouTubeIframeAPIReady 函数未调用

标签 javascript jquery youtube-api

我想调用 onYouTubeIframeAPIReady 函数,但这没有触发。我在控制台中仅获得 frameID,但其他函数没有被调用。

$(document).ready(function(){
    var player;
    var ytsrc = $('.video_holder_frame').find('iframe').attr('src');
    if (ytsrc) ytsrc = ytsrc.match(/youtube.com\/embed\/([^\\?]*)/i);
    if (!ytsrc) return;
    var frameID = 'youtube_' + ytsrc[1];    
    console.log(frameID);
    $('.video_holder_frame').find('iframe').attr('id', frameID);

    function attachToYoutubeFrame() {
        console.log("attachToYoutubeFrame");
        function onytplayerStateChange(newState) {
            console.log("onytplayerStateChange");
            console.log(newState);
        };

        player = new YT.Player(frameID, {
            events: {
                "onStateChange": onytplayerStateChange
            }
        });
    };

    function onYouTubeIframeAPIReady() {
        attachToYoutubeFrame();
    };
});

最佳答案

您的 onYouTubeIframeAPIReady() 函数必须全局定义。只需更换线路

function onYouTubeIframeAPIReady() {

window.onYouTubeIframeAPIReady = function() {

加载 youtube iframe api 库文件也很重要:

<script type="text/javascript" src="https://www.youtube.com/iframe_api"></script>

此外,您的 iframe src url 必须附加enablejsapi=1 参数:

http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1

关于javascript - onYouTubeIframeAPIReady 函数未调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26780291/

相关文章:

javascript - 切换和 JavaScript : Can't Get It To Work

javascript - 无法为表格制作固定标题

php - 如何获取特定类别中点赞数超过 X 的 YouTube 视频列表

javascript - 如何为 Canvas 上的对象编写 "drag"事件?

javascript - 速记符号中的无类对象

javascript - 悬停在父文本上的下拉菜单

html - YouTube iframe用户列表自动播放

javascript - 如何使用 youtube iframe api 检查 youtube 中的视频是否实时或上传

javascript - 如何更改 chart.js 中的 X 轴间隔

javascript - jQuery:查找 H2 id 并附加具有相同 id 的链接