Cannot modify content of iframe, what is wrong?

无人久伴 提交于 2019-12-17 06:15:13

问题


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

This is my 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

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

回答1:


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

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

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

Try this:

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



回答2:


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.ready of the parent page fires.

You could try changing your frame.load to frame.ready as .ready will fire immediately if it is bound after the ready event has already triggered.




回答3:


You would do something like this:

You set the src attribute of your iFrame to a blank page (blank.htm) or "", then in the ready handler you change the src to 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");
});


来源:https://stackoverflow.com/questions/11658011/cannot-modify-content-of-iframe-what-is-wrong

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!