gpt4 book ai didi

javascript - Youtube Iframe Api 无法在函数内工作

转载 作者:行者123 更新时间:2023-11-28 05:14:35 30 4
gpt4 key购买 nike

出于某种原因,当我将 YouTube iframe api 放入这样的函数中时,它似乎不起作用

$.getVideo = (elem, id) => {
$.getScript("https://www.youtube.com/iframe_api")

var player;

function onYouTubeIframeAPIReady() {
player = new YT.Player(elem, {
videoId: id,
playerVars: {
autoplay: 1,
autohide: 1,
modestbranding: 0,
rel: 0,
showinfo: 0,
controls: 0,
disablekb: 1,
enablejsapi: 1,
iv_load_policy: 3
},
events: {
'onReady': onPlayerReady,
}
})
}

function onPlayerReady(event) {
event.target.mute()
}
}
$.getVideo('player', 'CmRih_VtVAs')

http://codepen.io/anon/pen/MbBRpV

但是当在函数之外运行时它似乎工作正常?我做错了什么?

我真的需要这个功能才能工作

最佳答案

onYouTubeIframeAPIReady 必须在全局范围内可用。

以调用上述函数的方式修改您的函数,然后加载库,并将玩家变量更新为新实例。

 var player; // global scope
$.getVideo = (elem, id) => {

var cb = () => {
player = new YT.Player(elem, {
videoId: id,
playerVars: {
autoplay: 1,
autohide: 1,
modestbranding: 0,
rel: 0,
showinfo: 0,
controls: 0,
disablekb: 1,
enablejsapi: 1,
iv_load_policy: 3
},
events: {
'onReady': onPlayerReady,
}
})
}

window.onPlayerReady = function(event) {
event.target.mute();
}

// Load YouTube SDK if not loaded
if (!window.YT) {
$.getScript("https://www.youtube.com/iframe_api");
// update the global function to call cb
window.onYouTubeIframeAPIReady = cb;
// call cb()
} else {
window.onYouTubeIframeAPIReady = () => { }; // set it to dummy function
cb();
}

}

$.getVideo('player', 'CmRih_VtVAs')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="player"></div>

 var player; // global scope
$.getVideo = (elem, id) => {

var cb = () => {
player = new YT.Player(elem, {
videoId: id,
playerVars: {
autoplay: 1,
autohide: 1,
modestbranding: 0,
rel: 0,
showinfo: 0,
controls: 0,
disablekb: 1,
enablejsapi: 1,
iv_load_policy: 3
},
events: {
'onReady': onPlayerReady,
}
})
}

// make this global
window.onPlayerReady = function(event) {
event.target.mute();
}

// Load YouTube SDK if not loaded
if (!window.YT) {
$.getScript("https://www.youtube.com/iframe_api");
// update the global function to call cb
window.onYouTubeIframeAPIReady = cb;
// call cb()
} else {
window.onYouTubeIframeAPIReady = () => { }; // set it to dummy function
cb();
}

}

关于javascript - Youtube Iframe Api 无法在函数内工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41083437/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com