jjzjj

javascript - onYouTubeIframeAPIReady 里面 jQuery(document).ready

coder 2024-12-10 原文

我想做的是:

  1. 等待文档呈现;
  2. 当 YouTube iframe api 准备就绪时,初始化我的自定义函数并将 YT 对象传递给它,以便我可以从内部构建播放器。

这是我到目前为止所做的。它有效,但我觉得有些不对劲。我不确定应该这样做。

jQuery.getScript("http://www.youtube.com/iframe_api"); // load YT api

jQuery(document).ready(function() {
  onYouTubeIframeAPIReady = function() {
    new my_custom_function().init(YT); // init my function and pass YT object
  };
});

如果有人能阐明执行此操作的最佳方法,我将不胜感激。我确实需要从 my_custom_function() 内部构建播放器。

最佳答案

由于 onYouTubeIframeAPIReady 函数必须在全局范围内,我想我们不能在 jQuery 的文档就绪回调中绑定(bind)它。我看到的解决方法之一是使用 jQuery deferred objects .首先我们创建一个延迟对象并在 onYouTubeIframeAPIReady 回调

中解析它
 var YTdeferred = $.Deferred();
 window.onYouTubeIframeAPIReady = function() {
   YTdeferred.resolve(window.YT);
 };

然后在文档准备好之后等待延迟对象被解析

$(document).ready(function() {
  YTdeferred.done(function(YT) {
    // use YT here
  });
});

See the full example on JSFiddle

关于javascript - onYouTubeIframeAPIReady 里面 jQuery(document).ready,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17753525/

有关javascript - onYouTubeIframeAPIReady 里面 jQuery(document).ready的更多相关文章

随机推荐