我在模板上有一个嵌入的youtube视频,动态地插入了源,我的客户希望自己决定是否可以在该部分中包含图像或youtube视频。
我正在尝试做的是拥有将查找iframe src是否为空以及是否显示图像的代码。我觉得我已经很接近了,但是我需要帮助使其正常工作。
的HTML
<div class="col-sm-8 product-video-section">
<iframe id="ytplayer" width="560" height="315" src="youtubelink" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen wmode="Opaque"></iframe>
<img class="videoImg" style="display: none;" src="imgLink" />
</div>
JS
if ($('.product-video-section iframe').contents().find("body").length == 0) {
//alert("This is the IF");
}
else {
//alert("this is the ELSE");
$('.product-video-section iframe#ytplayer').remove();
$('.product-video-section .videoImg').css('display', 'block');
}
有人可以帮我指出我哪里出错了吗?
最佳答案
您可以使用attr测试iframe来源属性
if (!$('iframe#empty').attr('src'))
{
alert('empty');
}
if (!$('iframe#notempty').attr('src'))
{
alert('empty too');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<iframe id="empty" src="">
</iframe>
<iframe id="notempty" src="www.stackoverflow.com">
</iframe>
请注意,如果有多个元素符合您的选择,则需要对每个元素进行迭代