我有 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
$(".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中删除?
答案 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);
});
<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;
答案 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);
});