iframe一般是頁面內嵌的一個外部文件,咱們能夠經過Javascript訪問iframe對象並操做iframe內嵌文件裏面的DOM和Javascript對象。代碼以下:javascript
主頁面文件index.htmlhtml
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>index - iframe內部對象調用與反向調用[iTsai]</title> </head> <body> <h3>頁面最好在web容器(如:mongoose)中打開,chrome不支持iframe內函數離線調用</h3> <iframe id="ifrm" name="ifrm" src="iframe.html" width="800" height="200"></iframe> <br> <br> <input type="button" value="獲取iframe文本框內容" onclick="getIframeTxt()"> <input type="button" value="執行iframe頁面函數 i_foo()" onclick="call_i_foo()"> <input type="text" value="父頁面文本框內容" id="p-txt"> <script type="text/javascript"> function p_foo(){ alert('調用父頁面 p_foo() 函數'); } function getIframeTxt(){ var iWindow = window.frames[0];//獲取iframe頁面window對象 var iDocument = iWindow.document;////獲取iframe頁面document對象 var txt = iDocument.getElementById("i-txt").value; alert(txt); } function call_i_foo(){ window.frames[0].i_foo(); } </script> </body> </html>
子頁面文件iframe.htmljava
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>iframe - iframe內部對象調用與反向調用[iTsai]</title> </head> <body> <h2>iframe</h2> <hr/> <input type="button" value="獲取父頁面文本框內容" onClick="getParentTxt()"/> <input type="button" value="執行父頁面函數 p_foo()" onClick="call_p_foo()"/> <input type="text" value="iframe頁面文本框內容" id="i-txt"> <script type="text/javascript"> function i_foo(){ alert('調用iframe面 i_foo() 函數'); } function getParentTxt(){ var pWindow = window.parent;//獲取父頁面window對象 var pDocument = pWindow.document;////獲取父頁面document對象 var txt = pDocument.getElementById("p-txt").value; alert(txt); } function call_p_foo(){ window.parent.p_foo(); } </script> </body> </html>
頁面最好在web服務器(如:mongoose)中打開,chrome不支持離線iframe內函數調用,被認爲是不安全的腳本訪問。web