我需要用youtube的API加载多个视频。这是我第一次使用它,所以我不知道我做错了什么,但这是我正在尝试的:
var player;
var player2;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
videoId: 'hdy78ehsjdi'
});
player2 = new YT.Player('player', {
videoId: '81hdjskilct'
});
}
9条答案
按热度按时间wgxvkvu91#
由于
onYouTubeIframeAPIReady
函数应该只调用一次,因此可以使用以下方法:ControlId,width,height,VideoId
)保存在数组中onYouTubeIframeAPIReady
函数创建所有视频播放器示例
baubqpgj2#
新的YT.Player的第一个参数需要是HTML元素的id(例如DIV),该元素将被替换为视频的iframe。当您对这两个对象使用'player'时,您将把它们加载到同一个元素中。
函数的参数在Youtube API文档中进行了描述:
https://developers.google.com/youtube/iframe_api_reference#Loading_a_Video_Player (EDIT:更改为正确的链接)
jv2fixgn3#
HTML
视频JS
然后,创建这样的视频
tp5buhyn4#
我有一个更广泛的问题,归结为这个相同的问题。我的要求是写一个JS类来管理一个或多个(数字可以从1到无穷大)视频嵌入。后端系统是ExpressionEngine主要目标是建立一个分析框架,将个人数据推送到我们的Adobe Analytics平台。这里显示的只是发挥作用的部分,它可以从这里扩展很多。
CMS允许编辑在页面上创建模块来呈现视频。每个模块一个视频。每个模块基本上是通过Bootstrap 3排列的HTML的一部分(与这个答案无关)。
相关的HTML如下所示:
显示“{innov_mod_ytplayer:id}”的部分是来自CMS的YouTube视频ID。这允许每个嵌入项目有一个唯一的ID。这在后面很重要。
在这下面,我再渲染出来:
你也会在这里看到一些ExpressionEngine模板标签--这些只是YouTube上的视频ID和视频标题。要复制这些,你当然需要更改它们。
这样做的目的是允许我为每个新嵌入的视频使用新代码动态更新单个全局回调函数。这个回调将包含对我的类的示例的调用。你需要这些try/catch块,因为它会对所有“其他”嵌入抛出一个误报错误,除了它“现在”实际执行的嵌入--记住这个脚本对页面上的每个嵌入都运行一次。这些错误是预期的,实际上不会造成任何问题,因此try/catch会抑制这些错误。
使用CMS模板标记,我基于YouTube视频ID创建每个示例。如果有人多次添加同一个视频模块,我会遇到问题,但这是一个很容易处理的业务问题,因为这是不应该发生的。这允许我为每个视频反复示例化我的类的唯一示例。
该脚本的关键部分基于以下非常有用的SO答案:Adding code to a javascript function programmatically
这是实际的类。它主要是注解的...我们使用jQuery,所以你会在$.extend()方法中看到它的一个重要用途。我在类构造函数方法中使用它是为了方便,但是你也可以用vanilla JS(JavaScript equivalent of jQuery's extend method)来做这件事。我只是觉得jQuery更容易阅读,因为它对我可用,所以我使用它。
其他几点注意事项:
一旦解决了主要的全局回调问题,就很容易在类示例中保持作用域。只需添加.bind()。例如:
您可能还会看到:
这样示例的“this”作用域就不会意外丢失。也许没有必要,但这是我多年来一直采用的惯例。
无论如何,我已经为此工作了一个星期了,我想我应该与SO社区分享它,因为很明显,从我寻找答案,很多其他人也一直在寻找解决方案。
jhkqcmku5#
我在React中也需要同样的东西。扩展Vadim的答案,如果你不知道玩家数组之前是什么样子的,你可以像下面这样做,将它们添加到一个对象中,然后创建玩家。
mitkmikd6#
我所做的加载多个视频是破坏iframe当我点击视频外(你可以使用你想要的事件),然后我再次创建div,这样你就可以重用另一个视频ID的div
zzoitvuj7#
7uhlpewt8#
作为对瓦迪姆回答的补充,以下内容对我的事件很有效:
dauxcl2d9#