javascript - if/else 语句判断 Iframe 是否为空

标签 javascript jquery html iframe

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

相关文章:

Javascript 在 chrome 中有效,但在 IE 中无效

jQuery Raty 和 AngularJS

javascript - 事件函数问题

javascript - 如何从数组对象中获取最近或最接近的日期?

嵌入在 html 中的 javascript 未在 wkwebview 中运行

javascript - 如何使用 jQuery 为许多相似的父元素添加类

javascript - 由于 iframe 的导航,如何更改浏览器中的 URL?

html - CSS3 调整大小属性只允许增加 DIV 大小

html - 如何只为标签设置行高

javascript - jquery 尝试滑动一个已经打开的 div,创建一个 'bounce' 效果