【问题标题】:How to dynamically create multiple YouTube videos embedded to a page?如何动态创建嵌入到页面的多个 YouTube 视频?
【发布时间】:2016-03-07 19:11:04
【问题描述】:

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

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

<iframe id="koW2Clc0xEA" frameborder="0" allowfullscreen="1" title="YouTube video player" width="640" height="390" src="https://www.youtube.com/embed/koW2Clc0xEA?enablejsapi=1"></iframe>

我已经使用 YouTube JavaScript API 加载了一个英雄视频,我可以想象我可以使用该代码作为基本代码,但它属于网站的另一部分,然后是英雄视频。

【问题讨论】:

    标签: javascript jquery html iframe youtube


    【解决方案1】:

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

    在您的 HTML 中创建一个容器:

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

    JavaScript 与 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);
    }
    

    在这个例子中,我希望你的非序列化对象结构看起来像这样:

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

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

    【讨论】:

    • 谢谢。这就是我要找的!并且为 Norschleife +1 哈哈
    【解决方案2】:

    假设您的 JSON 字符串包含视频网址。这是一些适用于 jQuery 的代码。通过更改json_string 变量,它将更改加载到屏幕上的视频。

    <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 &lt;p&gt; tag instead of the iframe.

    【讨论】:

      猜你喜欢
      • 2015-11-30
      • 2015-06-01
      • 2012-08-02
      • 1970-01-01
      • 2015-06-09
      • 2012-02-16
      • 1970-01-01
      • 2018-06-27
      • 2014-01-20
      相关资源
      最近更新 更多