JQuery $('iframe').ready why doesn't w

2019-04-25 15:31发布

问题:

I have a very long iframe inside my parent page. When you reload or click on a link inside i frame's page it is loaded inside it but the purent window must be scroll up.

I have tried variuos code example:jquery which event is better thatn this and How to scroll parent page with iFrame reload Parent page body code:

<script language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
    $('iframe').load(function(){
         $(window).scrollTop(0);
    });
});</script>
<iframe frameborder="0" height="1000" id="iframe" src="http://mysite.com" width="800"></iframe>

And now this is my final code in parent page: (that doesn't work)

<script type="text/javascript">
$('iframe').ready(function(){
     $(window).scrollTop(0);
});
</script>
<iframe frameborder="0" height="1000" id="iframe" align="top" src="http://foicam.altervista.org/listadinamica.php" width="800" ></iframe>

but the problem is that each code scroll up the parent page AFTER the frame is compleately loaded (images include). Whant i want is that the parent page scrolls up BEFORE iframe has finished to load.

if you click on last image or scroll down the page and then reload only iframe you'll see what i mean!

Thanx a lot, and sorry but I discovered the existence of this language iesterday afternoon!!!

回答1:

Change your code to:

<iframe frameborder="0" height="1000" id="iframe" align="top" src="http://foicam.altervista.org/listadinamica.php" width="800" ></iframe>

<script type="text/javascript">
$('iframe').ready(function(){
     $(window).scrollTop(0);
});
</script>

Your script is being called before your iframe is part of your DOM. If you put your script after your iframe is part of your DOM, it will recognize it and $('iframe') will actually find the object.



回答2:

The script appears before the iframe in the source, and doesn't have anything to delay its execution (such as being called in onready).

Consequently, when it executes, the iframe has not been added to the DOM, and the selector doesn't find the frame. The event handler will only be bound to any iframes that appear earlier in the source.