我的模板上有一个嵌入式 YouTube 视频,其中源是动态拉入的,我的客户希望能够自行决定在该部分中包含图像或 YouTube 视频。
我想做的是编写代码来查找 iframes 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>
请注意,如果有多个元素与您的选择相匹配,您需要迭代每个元素
关于javascript - if/else 语句判断 Iframe 是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50116734/