javascript - YouTube iframe API——从 onPlayerStateChange 事件处理程序内部引用 Javascript 对象

标签 javascript iframe youtube

这是我的 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/

相关文章:

javascript - 如何更改 chrome ://flags using chrome API?

javascript - 停止在函数中提交表单 - jquery/javascript

iphone - 如何解析 Objective-C 中 iframe 标签的 src 属性?

jquery - 在 div/iframe 上使用 .remove 的替代方法

python-2.7 - 高效读写大型文件

javascript - 练习二维数组

javascript - AngularJS 中的字符串到对象

internet-explorer - IE 上的 iframe.print 与 window.print - 以前的小字体

php - 如何以分页方式从 YouTube 获取用户视频

android - 在基于Chromium的 float WebView中播放YouTube视频时出现音频滞后或断断续续的情况