这是我的 HTML 文件中正在运行的播放器。我希望 YT.PlayerState.ENDED
又名 event.data == 0
的处理程序能够引用客户端 Javascript 对象 (booth
) 存储 videoID,但 booth
未定义。做这样的事情的正确技术是什么?
function onPlayerStateChange(event) {
if (event.data == -1) {
player.playVideo();
}
if (event.data == 0) {
alert("This alert pops up");
alert(window.booth);
// Undefined -- even though "booth" is already instantiated in linked JS file
/*
window.booth.cue.index++;
event.target.loadVideoById(window.booth.cue.list[booth.cue.index].id);
*/
}
}
这是完整的Javascript file -- 第 16 行 socket.on('boothCreated'...
是实例化 booth
的处理程序,只有在那之后才创建播放器 -- 所以看起来我认为玩家应该能够引用这个。
最佳答案
我不需要再看下去,链接的 JS 文件的开头说明了一切:
window.onload = function () { // beginning of function closure
var user = null; // these are private variables inside the function
var booth = null; // these are private variables inside the function
// etc...
如果您希望这些变量在 window.booth
等中可见,那么您需要执行以下操作:
window.onload = function () { // beginning of function closure
window.user = null; // these are now public
window.booth = null; // these are now public
// etc...
您只是将它们设置为私有(private),因此“外部世界”看不到它们。
或者,如果您想在使用它们的同时保持它们的私密性,那么您需要以某种方式加入文件并将 onPlayerStateChange
函数放入 window.onload = function() { 中。 ..
.
关于javascript - YouTube iframe API——从 onPlayerStateChange 事件处理程序内部引用 Javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37766793/