如何动态创建嵌入页面的多个YouTube视频? [英] How to dynamically create multiple youtube videos embedded to a page?

查看:97
本文介绍了如何动态创建嵌入页面的多个YouTube视频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在页面上动态创建多个youtube嵌入。 Youtube视频ID存储在JSON对象中。

I was wondering if it is possible to create dynamically multiple youtube embeds on a page. Youtube video id's where stored in a JSON object.

我希望脚本可以动态创建这样的东西:

I was hoping something like this can be created dynamically by the script:

我已经使用Youtube Javascript API加载一个英雄视频,我可以想象我可以使用该代码作为基本,但它属于到网站的另一部分然后是英雄视频。有人有什么建议吗?

I already use the Youtube Javascript API to load one hero video, I can imagine that I may can use that code as the basic, but it belongs to another part of the site then the hero video. Anyone have any suggestions?

推荐答案

我为你准备了一个小JsFiddle: https://jsfiddle.net/v879x7bm/3/

I prepared a little JsFiddle for you: https://jsfiddle.net/v879x7bm/3/

HTML :

<div id="ytContainer"></div>

使用jQuery的JavaScript

var yourJsonAsString = '{"videos":[{"title":"bla bla","id":"no3unQcv_vg"},{"title":"blub","id":"3IHrNcJdP8s"},{"title":"abc","id":"-6v-rwoRv_4"}]}';

var ytVideos = JSON.parse(yourJsonAsString);

for (var i in ytVideos.videos) {
  var ytVideo = $("<iframe/>");
  ytVideo.attr({
    width: 560,
    height: 315,
    src: 'https://www.youtube.com/embed/' + ytVideos.videos[i].id,
    frameborder: 0
  });
  $("#ytContainer").append(ytVideo);
}

在这个例子中,我希望你的反序列化对象结构如下所示:

In this example I expected your unserialized object structure is looking like this:

{  
   "videos":[  
      {  
         "title":"bla bla",
         "id":"no3unQcv_vg"
      },
      {  
         "title":"blub",
         "id":"3IHrNcJdP8s"
      },
      {  
         "title":"abc",
         "id":"-6v-rwoRv_4"
      }
   ]
}

但是你可以适应你的需要:)

But you can adapt to your needs :)

这篇关于如何动态创建嵌入页面的多个YouTube视频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆