father.html通過iframe包含了son.html
father.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script type="text/javascript"> function say(){ alert("這是father的say()"); } function callChild(){ myFrame.window.say(); myFrame.window.document.getElementById("button").value="調用結束" } </script> </head> <body> <input id="button" type="button" value="調用son.html中的函數say()" onclick="callChild()"/> <iframe name="myFrame" src="son.html"></iframe> </body> </html>
son.html
<html> <head> <meta charset="utf-8" /> <script type="text/javascript"> function say() { alert("這是son的say()"); } function callParent() { parent.say(); parent.window.document.getElementById("button").value = "調用結束"; } </script> </head> <body> <input id="button" type="button" value="調用father.html中的say()函數" onclick="callParent()" /> </body> </html>
方法是如何調用的?獲取子頁面或父頁面的window對象,在通過對象調用方法。
父頁面調用子頁面方法:FrameName.window.childMethod();
子頁面調用父頁面方法:parent.window.parentMethod();
在方法調用前,以下點必須要注意!!!
在方法調用前,以下點必須要注意!!!
要確保在iframe加載完成后再進行操作,如果iframe還未加載完成就開始調用里面的方法或變量,會產生錯誤。判斷iframe是否加載完成有兩種方法:
1. iframe上用onload事件
2. 用document.readyState=="complete"來判斷
如果文章對你有幫助,麻煩幫忙點個贊哦!嘿嘿!做一個靠譜的技術博主!