if/else 语句来查找 Iframe 是否为空



我的模板上有一个嵌入式的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>

请注意,如果有多个元素与您的选择匹配,则需要迭代每个元素

最新更新