简体   繁体   中英

javascript proper way to call function

I'm not good in javascript but I find examples and usually understand it. But this is driving me crazy for the last hour. What I'm trying to do is to embed the list.php file to my mainpage.html using the IFRAME. This list.php is showing some links and when I click the link the result should be shown in another place on main page (I'm targeting some div). And those 3 functions are placed inside list.php file.

If I do this:

   function autoscroll() {
       window.parent.parent.scrollTo(0,0);
   }
   function resizeIframe(obj) {
       obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
   }
   function url2div(url,target){
       parent.document.getElementById(target).innerHTML = '<iframe style="width:100%;height:100%;" scrolling="no" frameborder="1" onload="javascript:resizeIframe(this); javascript:autoscroll();" src="' + url + '" />';
   }   

So if I call the autoscroll() function within my IFRAME like this

onload="javascript:autoscroll();"

autoscroll doesn't work (everything else is working).

But if I put it directly in IFRAME like this:

onload="javascript:window.parent.parent.scrollTo(0,0);"

then it works!

What's wrong with first approach?

It sounds like you're putting the script element in your main page, but then trying to use it in an iframe on the page. Also, you're using window.parent.parent which goes two levels up the containment hierarchy, which seems suspicious.

The iframe and the main window are two different environments. Globals (like your autoscroll ) in the main page are not in scope for the iframe 's code.

The iframe can access the parent window's globals, provided they're from the same origin, via the parent symbol:

parent.autoscroll();

Then use window , or window.paren , depending on whether you want to scroll the parent or its parent.

It's all about being relative to the document in which the script is included.

Since that was clear as mud: Let's assume your goal is to scroll the main window that the iframe is in:

Option 1 : Put it in the iframe (probably best):

In the main window:

Nothing.

In the iframe

<script language="JavaScript">
   function autoscroll() {
       window.parent.scrollTo(0,0); // <== Only one `parent`, if you want the iframe's parent
   }
</script>

and

onload="autoscroll();"

Or :

Option 2 : Put it in the main window:

In the main window:

<script language="JavaScript">
   function autoscroll() {
       window.scrollTo(0,0); // <== No `parent` at all, if you want the main window
   }
</script>

In the iframe :

onload="parent.autoscroll();"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM