使用jQuery修改iframe的HTML内容



我有一个html页面,有一个iframe与src属性指向另一个html页面,其中已经有一些内容。

parent.html

<body>
    <iframe src="child.html"></iframe>
</body>

child.html

<body>
    <p>test1</p>
</body>

parent.html也有一个jquery函数,它尝试在child.html的主体上追加一个段落:

$(function(){
    var $iframe = $("iframe");
    $iframe.ready(function(){
        $iframe.contents().find("body").append("<p>test2</p>");
    });
});

问题是函数不工作,段落没有被添加。有趣的部分是,如果我从iframe的src属性中删除"child.html",则该段落将被添加到空白的html页面中。

是不可能从iframe修改html文档的内容(当文档已经包含了一些元素)?

同时,跨域策略也没有任何问题。

看起来代码是在iframe内容实际加载之前执行的。试试下面的代码:

$(document).ready(function(){
    var $iframe = $("iframe");
    $iframe.on('load', (function(){
        $iframe.contents().find("body").append("<p>test2</p>");
    });
});

最新更新