How to dynamically create multiple youtube videos

2019-05-23 00:51发布

问题:

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:

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?

回答1:

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

Create a container in your HTML:

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

JavaScript with jQuery:

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 :)



回答2:

Imagine that your JSON string that contains the video urls. Here is some code that will work with jQuery. By changing the json_string variable, it will change which videos get loaded to the screen.

<html>
  <div id="content_div"></div>
</html>

<script type="text/javascript">

jQuery(function () {

  var json_string = '{ "vid1" : "www.vid1.url", "vid2" : "www.vid2.url"}';

  //make the string into an object
  var json_object = JSON.parse(json_string);

  //loop through the json_object and add the new video each time through
  for (i in json_object) {
    jQuery("#content_div").append('<p><iframe width="420" height="315" src="' + json_object[i] + '"></iframe></p>');
  }

});

</script>

JSfiddle here showing the code working, but using a <p> tag instead of the iframe.