使用jQuery修改iframe的HTML内容 [英] Modifying the HTML content of an iframe using jQuery

查看:1224
本文介绍了使用jQuery修改iframe的HTML内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html页面,该页面的iframe的src属性指向另一个已经包含一些内容的html页面.

I have an html page that has an iframe with the src attribute pointing to another html page which already has some content in it.

parent.html

parent.html

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

child.html

child.html

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

parent.html还具有一个jquery函数,该函数尝试将一个段落附加到child.html的正文中:

parent.html also has a jquery function that tries to append a paragraph to the body of child.html:

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

});

问题是该功能不起作用,未添加该段落.有趣的是,如果我从iframe的src属性中删除"child.html",则该段落将被添加到空白的html页面中.

The problem is that the function is not working, the paragraph is not being added. The interesting part is that if I remove "child.html" from the src attribute of the iframe, the paragraph is being added into a blank html page.

是否无法通过iframe修改html文档的内容(当文档中已经包含许多元素时)?

Is it not possible to modify the content of an html document from an iframe (when the document already contains a number of elements)?

此外,跨域策略也没有任何问题.

Also, there isn't any problem with the cross-domain policy.

谢谢.

推荐答案

在iframe内容实际加载之前,代码似乎正在执行.尝试以下代码:

It looks like the code is executing before the iframe contents has actually loaded. Try this code:

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

这篇关于使用jQuery修改iframe的HTML内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆