无法从iframe访问父元素

时间:2015-02-24 08:27:21

标签: javascript iframe

我不明白。我以为我做了它,现在我不能这样做。 带iframe的简单html。 iframe是另一个HTML。我想在您访问iframe时更改主iframe中的图片。 来自主html的HTML:

主要HTML:

<!DOCTYPE HTML>
 <html lang="en">
    <head></head>
    <body>
        <img id="logo" src="../img/fpdfilms-logo-home.png" />
        <iframe id="fondo" name="main" src="test.html"></iframe>
    </body>
</html>

的test.html

<!DOCTYPE HTML>
 <html lang="en">
    <head></head>
    <body>
        <a href="#" onclick="change();">Change Picture</p>
        <script src="../js/jquery-1.11.2.min.js"></script>
        <script type="text/javascript">
            function change()
            {
                var $logo= $('#logo', window.parent.document);
                alert("Does it work?");
                $logo.attr("src","../img/fpdfilms-logo-director.png");
            }
        </script>
    </body>
</html>

单击链接时应该更改图片。但ALERT没有显示......我尝试过不同的方式而且我真的输了。难以实现这种简单的改变吗​​?

2 个答案:

答案 0 :(得分:1)

您可以参考这个答案,因为它可以满足您对jquery的需求。

how to access iFrame parent page using jquery?

从上面的示例中选择父文档中iframe的元素,使用

var $parentElement= $('#parentElement', window.parent.document);

答案 1 :(得分:0)

检查了您的页面(chrome 40)并获得了

SecurityError: Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.

所以我检查了服务器(本地快递)并且工作正常。