jQuery 无法修改iframe的内容,有什么问题?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11658011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:48:23  来源:igfitidea点击:

Cannot modify content of iframe, what is wrong?

jqueryhtml

提问by Slay

I am trying to modify content of an iframe but it does not work.

我正在尝试修改 iframe 的内容,但它不起作用。

This is my main.html

这是我的 main.html

<html>
<head><title>Main page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>

<h3>Main page</h3>
<iframe src="ifr.htm" id="ifr" name="ifr"></iframe>
</body>

<script>
$(document).ready(function(){
    $('#ifr').load(function(){
        $('#ifr').contents().find('body').html('Hey, i`ve changed content of <body>!    Yay!!!');
    });
});

</script>
</html>

This is my ifr.htm

这是我的ifr.htm

<html>
<head><title>Iframe page</title></head>
<body>
 Content to be displayed in iframe ...
</body>
</html>

回答by Oscar Jara

Please don't forget the cross-domainpolicy, otherwise it won't work.

请不要忘记cross-domain政策,否则将无法正常工作。

Live demo:http://jsfiddle.net/oscarj24/wTWjF/

现场演示:http : //jsfiddle.net/oscarj24/wTWjF/

(Just to know, I am not using a 404 page, take a look)

(只是想知道,我没有使用 404 页面,请看一看)

Try this:

尝试这个:

$(document).ready(function(){
    $('#ifr').ready(function(){
        $(this).contents().find('body').html('Hey, I have changed the body content yay!');
    });
});?

回答by jbabey

Assuming you are honoring the cross-domain policy, this sounds like a timing issue. Chances are your iframe has already finished loading when the document.readyof the parent page fires.

假设您遵守跨域策略,这听起来像是一个时间问题。当document.ready父页面的 触发时,您的 iframe 可能已经完成加载。

You could try changing your frame.loadto frame.readyas .readywill fire immediately if it is bound after the ready event has already triggered.

如果在就绪事件已经触发后绑定它,您可以尝试将其更改frame.loadframe.readyas.ready将立即触发。

回答by M. Abbas

You would do something like this:

你会做这样的事情:

You set the srcattribute of your iFrameto a blank page (blank.htm) or "", then in the ready handler you change the src to ifr.htm.

您将您的src属性设置iFrame为空白页 (blank.htm) 或 "",然后在就绪处理程序中将 src 更改为ifr.htm

$(document).ready(
    $('#ifr').load(function(){
        $(this).contents().find('body').html('Hey, i`ve changed content of <body>!    Yay!!!');
    });
    $('#ifr').attr("src", "ifr.htm");
});