【问题标题】:Dynamically load iframe on click点击时动态加载 iframe
【发布时间】:2017-12-19 09:36:59
【问题描述】:

我有一个 bootstrap 3 列 youtube 视频

<div class="col-md-4">
  <div class="video_img_wrapper">
    <img class="video_img" data-toggle="modal" class="ytVideo" id="'.$item->id->videoId.'" data-target="#myModal_'.$item->id->videoId.'" src="'.$thumbnailUrl.'" />
    <img src="'.get_bloginfo('template_url').'/assets/img/playicon-nl.png" class="fa-play-circle-o" aria-hidden="true" data-toggle="modal" data-target="#myModal_'.$item->id->videoId.'" />
  </div>
  <div class="video_title"><span>'. $item->snippet->title .'</span></div>
</div>

<div class="modal fade youtube-modal" id="myModal_'.$item->id->videoId.'" role="dialog">
  <div class="modal-dialog">
    <div class="modal-body" id="videoModalBody"></div>
  </div>
</div>

我在 #videoModalBody div 中使用 jquery 注入 iframe

$(".video_img").click(function(evt){
  var videoId = $(this).attr("id");
  var iframe = '<iframe enablejsapi=1 id="myModal_'+videoId+'" width="850" height="500" src="https://www.youtube.com/embed/'+videoId+'" frameborder="0" allowfullscreen></iframe>';
  $("#videoModalBody").append(iframe);
});

如何更改我的 Javascript,以便当我点击另一个视频时,前一个视频会从 DOM 中删除?

【问题讨论】:

    标签: javascript jquery iframe


    【解决方案1】:

    您可以在iframe 上设置一个全局class,然后在添加新的iframe 之前删除所有@:

    $('.globalIframe').remove();
    $("#videoModalBody").append(iframe);
    

    $(".video_img").click(function(evt) {
      var videoId = $(this).attr("id");
      var iframe = '<iframe enablejsapi=1 id="myModal_' + videoId + '" class="globalIframe" width="850" height="500" src="https://www.youtube.com/embed/' + videoId + '" frameborder="0" allowfullscreen></iframe>';
      $('.globalIframe').remove();
      $("#videoModalBody").append(iframe);
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a class="video_img">Click Me</a>
    <div id="videoModalBody"></div>

    【讨论】:

      【解决方案2】:

      你可以通过类名来引用它,或者将引用存储在一个变量中,IE:

      var videoId = null; // Shared reference
      $(".video_img").click(function(evt){
          if (videoId) $('#'+videoId).remove(); //remove previous videos if present
          videoId = $(this).attr("id"); //store new id
          var iframe = '<iframe enablejsapi=1 id="myModal_'+videoId+'" width="850" height="500" src="https://www.youtube.com/embed/'+videoId+'" frameborder="0" allowfullscreen></iframe>';
                    $("#videoModalBody").append(iframe);
                });
      

      【讨论】:

        猜你喜欢
        • 2015-06-20
        • 1970-01-01
        • 2012-05-22
        • 2018-09-10
        • 2016-09-07
        • 1970-01-01
        • 1970-01-01
        • 2017-12-03
        • 1970-01-01
        相关资源
        最近更新 更多