单击时动态加载iframe

时间:2017-12-19 09:37:00

标签: javascript jquery iframe

我有 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中删除?

2 个答案:

答案 0 :(得分:1)

您可以在class上设置全局iframe,然后在添加新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);

});

&#13;
&#13;
<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>
&#13;
s.ehlo()
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以按类名引用它或将引用存储在变量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);
          });