简体   繁体   English

检查是否存在iFrame内容

[英]Checking if iFrame content exists

I'm working with two if statements in a jQuery each statement that look for an iFrame within the body of an element and sets the height accordingly if it's empty or if it has content. 我正在使用jQuery中的两个if语句,每个语句在元素的主体内查找iFrame并相应地设置高度(如果它为空或具有内容)。 I'm using this to check if DFP has served an advert or if it has served a blank. 我正在使用它来检查DFP广告管理系统是否投放了广告或是否投放了空白广告。

What I have is the following: 我有以下内容:

$('.element-paragraph').each(function(index) {
    var characterCount = $(this).text().length
    totalCount = totalCount + characterCount

    if (totalCount > 1200)  {
        totalCount = 0;
        var feedData = "pos" + adUnit.toString();
        var advertInsert = '<div id=' + feedData +  ' class="inline-ad big-box-300x250 border-bottom-" data-mobile-display="" data-desktop-display="" data-ad-type="' + feedData + '" style=""></div>'
        var ad_script = '<script type="text/javascript">googletag.cmd.push(function() { googletag.display("' + feedData + '"); });</script>';
        $(this).append(advertInsert)
        $(this).append(ad_script);

        adUnit++;

        if ($("#" + feedData).contents().find("iframe").find("body").length > 0) {
            console.log("Advert found for unit" + feedData)
            $("#" + feedData).css("height","350");
        }

        else {
            console.log("Advert not found for unit" + feedData)
            $("#" + feedData).css("height","0");
        }
    }
});

The content is nested like so: #id > iFrame > div > div > #document > html > body 内容是这样嵌套的: #id > iFrame > div > div > #document > html > body

It doesn't seem to be properly checking the length of the body within the iFrame. 似乎无法正确检查iFrame中的主体长度。 If I remove the else statement it adjusts the height properly but is doing so for every advert that runs through the loop instead of just the ones it finds content for. 如果我删除else语句,它将正确调整高度,但这样做是针对循环中的每个广告,而不只是针对其找到内容的广告。

You should use .contents() to reveal iframe document. 您应该使用.contents()来显示iframe文档。

$("#iframe_container").find("iframe").contents().find("body")

In your case: 在您的情况下:

$("#" + feedData).find("iframe").contents().find("body").contents().length > 0

because empty iframe does have body 因为空的iframe 确实有主体

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM