1. 當我們在父頁面中需要調用iframe標簽中嵌入的子頁面中的js方法時,可以使用:
document.getElementById(iframe的id).contentWindow.childtest();
iframe的id:指的是需要調用的子頁面的iframe的id;
childtest():是子頁面中的js方法,夫頁面就是要調用子頁面的這個方法。
2.當在子頁面中需要調用父頁面中的方法時,使用如下js:
window.parent.parenttest();
具體代碼:
父文件
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Parent Page</title> <style> h1, input { margin-left: 50px } input { border: none; background: #317ef3; color:#fff; border-radius:3px; padding:5px 10px; margin-bottom:10px; } #childframe{ border:1px solid green; margin: 0 50px; } #childframe1 { border: 1px solid #f00; } </style> <script type="text/javascript" src="js/jquery-1.12.4.min.js"></script> <script language="javascript" type="text/javascript"> //// 方法1: // //父元素的方法 // function parenttest() { // alert("這是父頁面的方法!"); // } // //調取iframe 子元素頁面childtest()的方法 // function btnClick1() { // document.getElementById("childframe").contentWindow.childtest(); // // $("#childframe")[0].contentWindow.childtest(); // } //方法2 $(function () { //調取iframe 子元素頁面childtest()的方法 function btnClick1() { $("#childframe")[0].contentWindow.childtest(); } $("#btn").click(function () { btnClick1() }) }) //父元素的方法 function parenttest() { alert("這是父頁面的方法!"); } </script> </head> <body> <div style="margin:auto;"> <h1 style="font-size:18px;color:green">iframe父子級別互調方法實現</h1> <!--<input type="button" id="btn" value="調用子頁面的方法" onclick="btnClick1()" />--> <input type="button" id="btn" value="調用子頁面的方法" /> </div> <div style="margin:auto;"> <iframe style="width:300px; height:300px;" id="childframe" src="ChildPage.html"></iframe> <iframe style="width:300px; height:300px;" id="childframe1" src="ChildPage1.html"></iframe> </div> </body> </html>
子文件
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Child Page</title> <style> h1{ font-size:18px; color:gold;} input { border: 1px solid #317ef3; background: none; color: #317ef3; border-radius: 3px; padding: 5px 10px; margin-bottom: 10px; } </style> <script language="javascript" type="text/javascript"> //function childtest() { // alert("這是子頁面的方法!"); // } var childtest = function () { alert("這是子頁面的方法!"); } function btnClick() { window.parent.parenttest(); } </script> </head> <body> <div style="margin:auto;"> <h1>This is the Child Page.</h1> <input type="button" value="調用父頁面的方法" onclick="btnClick()" /> </div> </body> </html>