【问题标题】:How to access the content of an iframe with jQuery?如何使用 jQuery 访问 iframe 的内容?
【发布时间】:2010-12-20 06:39:25
【问题描述】:

如何使用 jQuery 访问 iframe 的内容?我试过这样做,但它不起作用:

iframe 内容: <div id="myContent"></div>

jQuery: $("#myiframe").find("#myContent")

如何访问myContent


类似于 jquery/javascript: accessing contents of an iframe,但接受的答案不是我想要的。

【问题讨论】:

  • 我刚刚发现Firefox控制台中内置的$变量看起来根本不像一个完整的jQuery。 (我在意识到我也没有 jQuery 变量之后想到了这一点,然后发现我没有加载 jQuery 的源代码)。

标签: jquery iframe


【解决方案1】:

你必须使用contents()方法:

$("#myiframe").contents().find("#myContent")

来源:http://simple.procoding.net/2008/03/21/how-to-access-iframe-in-jquery/

API文档:https://api.jquery.com/contents/

【讨论】:

  • 给我错误:错误:访问属性“ownerDocument”的权限被拒绝
  • ime:由于以下原因,它可能会给您错误:1)Iframe 不属于同一个域。 2)您试图在 iframe 加载事件之前阅读它。
  • 在尝试访问 iframe 内容并出现错误之前,有没有办法验证 iframe 内容是否来自同一个域?
  • 源网址坏了。
  • @jperezmartin:您将不得不使用一些 javascript 库来在主页和 iframe 之间传输信息。由于跨浏览器功能,基本上它被浏览器拒绝。对不起,我不知道有任何这样的库,因为我从来不需要它。
【解决方案2】:
<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">

$(function() {

    //here you have the control over the body of the iframe document
    var iBody = $("#iView").contents().find("body");

    //here you have the control over any element (#myContent)
    var myContent = iBody.find("#myContent");

});

</script>
</head>
<body>
  <iframe src="mifile.html" id="iView" style="width:200px;height:70px;border:dotted 1px red" frameborder="0"></iframe>
</body>
</html>

【讨论】:

    【解决方案3】:

    如果 iframe 的来源是外部域,浏览器将隐藏 iframe 内容(同源策略)。 一种解决方法是将外部内容保存在文件中,例如(在 PHP 中):

    <?php
        $contents = file_get_contents($external_url);
        $res = file_put_contents($filename, $contents);
    ?>
    

    然后,获取新的文件内容(字符串)并解析为html,例如(在jquery中):

    $.get(file_url, function(string){
        var html = $.parseHTML(string);
        var contents = $(html).contents();
    },'html');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-24
      相关资源
      最近更新 更多