JQuery在iFrame

时间:2018-01-24 03:20:58

标签: javascript jquery html iframe

我想在iFrame中找到HTML内容。我遵循此代码,但似乎无效:

$('#iviFrame1').contents().find('#iViTag1').html();

iFrame完全加载后,我在Firefox控制台上执行。

我还检查了我的iFrame及其中的内容,并找到了id为iViTag1的div:

<iframe
    id="iviFrame1"
    name="iVi Dashboard"            
    longdesc="iVi - Your Personal Dashboard"
    style="display:inline"
    src=""
    width="100%"
    height="98%"
    align="middle"
    frameborder="0"
    marginwidth="0"
    marginheight="0"
    scrolling="auto"></iframe>
在iframe中

<div id="iViTag1" style="display: none;"></div>

我在Firefox控制台和控制台输出$('#iviFrame1').contents().find('#iViTag1').html();

上做underfined

这是我试过的:

$('#iviFrame1').contents();
Object { length: 0, prevObject: {…}, context: HTMLDocument http://localhost:8080/WS_ivi/?p=8&o={7f377407-04cc-464e-ac78-17738486e94a}&v=1.7.5.8 }
$('#iviFrame2').contents().find('#iViTag1');
Object { length: 0, prevObject: {…}, context: HTMLDocument http://localhost:8080/WS_ivi/?p=8&o={7f377407-04cc-464e-ac78-17738486e94a}&v=1.7.5.8, selector: "#iViTag1" }

$("#iViTag1");
{…}
context: HTMLDocument http://localhost:8080/WS_ivi/?p=8&o={7f377407-04cc-464e-ac78-17738486e94a}&v=1.7.5.8
selector: "#iViTag1"
__proto__: Object { jquery: "2.1.4", constructor: n(), length: 0, … }

顺便说一句,我使用的是Firefox Quantum 57,JQuery 2.1.4和我的iFrame SRC来自不同的IP。我在另一台服务器上使用了localhost和iFrame SRC。

我已经采用了任何方法,并且不起作用。如果我从检查员那里检查,我看到iViTag1存在。

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

最好的猜测是你没有使用加载事件处理程序来在查找元素之前加载iframe页面:

$(function()
    $('#iviFrame1').on('load', function(){
       var $iV = $(this).contents().find('#iViTag1');
       console.log('iv len=', $iV.length)
    });
});

答案 1 :(得分:0)

因为:

可能会给你错误
  1. Iframe不属于同一个域。

  2. 您正试图在Iframe加载事件之前阅读它。

  3. 请参阅jQuery/JavaScript: accessing contents of an iframe

    您可能需要查看Ways to circumvent the same-origin policy