使用 jquery 访问 colorbox Iframe 内容



我尝试访问由jquery colorbox插件生成的iframe的内容,几个小时都没有成功。

这是我的代码:

    $(".ListView li a").colorbox({ 
iframe:true,
width: "50%",
height: "50%",
opacity: 0.5,
onComplete: function() { 
alert("complete");
$("iframe").contents().find("p").css("color","#f00");   
}
});

加载一个文件并显示它。 太好了。 当 iframe ist 加载完成时,也会抛出警报消息。但是我无法通过 jquery 选择器访问框架内的元素。iframe 内的所有 p 元素都不会发生任何变化。

也不

    if($("iframe").contents().length > 0)
{
alert("exists");    
}

也不

    if($("iframe").length > 0)
{
alert("exists");    
}

都成功了。页面上没有其他 iframe,我也尝试插入类名。

对于直接插入 html 而不是由 colorbox 生成的"普通"iframe,我的函数正在工作。

谢谢

生成的代码:

<div id="colorbox" class="" style="display: block; padding-bottom: 50px; padding-right: 50px;    top: 128px; left: 476px; position: absolute; width: 902px; height: 207px;">
<div id="cboxWrapper" style="height: 257px; width: 952px;">
<div>
<div style="clear: left;">
<div id="cboxMiddleLeft" style="float: left; height: 207px;"></div>
<div id="cboxContent" style="float: left; width: 902px; height: 207px;">
<div id="cboxLoadedContent" style="display: block; width: 902px; overflow: auto; height: 187px;">
<iframe class="cboxIframe" frameborder="0" name="cbox1334265249803" src="qtest.html">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<body>
<a href="#">Link</a>
<p>Formatted Text</p>
</body>
</html>
</iframe>
</div>
<div id="cboxLoadingOverlay" style="float: left; display: none;"></div>
<div id="cboxLoadingGraphic" style="float: left; display: none;"></div>
<div id="cboxTitle" style="float: left; display: block;"></div>
<div id="cboxCurrent" style="float: left; display: none;"></div>
<div id="cboxNext" style="float: left; display: none;"></div>
<div id="cboxPrevious" style="float: left; display: none;"></div>
<div id="cboxSlideshow" style="float: left; display: none;"></div>
<div id="cboxClose" style="float: left;">close</div>
</div>
<div id="cboxMiddleRight" style="float: left; height: 207px;"></div>
</div>
<div style="clear: left;">
</div>
<div style="position: absolute; width: 9999px; visibility: hidden; display: none;"></div>
</div>
<div class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-draggable" style="display: none; z-index: 1000; outline: 0px none;" tabindex="-1" role="dialog" aria-labelledby="ui-dialog-title-box-trash-dialog">

对于 iframes,onComplete 实际上会在将 iframe 元素添加到文档后立即触发。 如果要查询内容,则必须等到 DOM 准备就绪。 父文档无法知道 iframe 的 DOM 何时准备就绪,它只能侦听窗口的 onload 事件。

但是,您可以通过将 fastIframe 属性设置为 false 来告诉 colorbox 等待并在触发 iframe 的 onload 事件后触发 onComplete 函数。 例:

$('a.example').colorbox({iframe:true, fastIframe:false, width:500, height:500})

当然,这一切都假设 iframe 与父级来自同一域,并且没有安全限制阻止您访问 iframe 的内容。

有一个 corss-browser 解决方案可以访问 iframe 的内容,你可以在这里阅读它。

此外,您可以使用jquery访问iFrame的内容,在此处阅读更多内容。

这两种解决方案都按 ID 查找您的 iframe,因此您需要一个 ID 才能使用这些解决方案。我希望这有所帮助。

最新更新