1. 程式人生 > >子頁面與父頁面的呼叫問題

子頁面與父頁面的呼叫問題

父頁面:

<html>
   <head>
       <title>iframe</title>
       <script type="text/javascript">
           function closeM(){

              document.getElementById("f").style.display="none";

       }


      </script>
   </head>
   <body>
       <div id="top" style="width:200px;height:300px;">
           hello        
       </div>
 <iframe  name="ifr_name"  id="f"   style="color:yellow"   src="b.html"  frameborder="no" scrolling="no"  width="776px"  


height="500px"/>
   </body>
</html>

子頁面b.html:

<!DOCTYPE html>
<html lang="zh">
<head>


   <title>-title-</title>
     <script type="text/javascript">
           function closeM(){
             window.parent.document.getElementById("f").style.display="none";


      }
    </script>
</head>
<body class="home"> 
    <div id="page" style="width:300px;height:200px;">
                
                <div class="confirmBt"  style="width:200px;height:100px;"><input type="button" value="


確認提交"  onclick="closeM();"></div>
                        
           
    </div>
</body>
</html>

如果試圖在子頁面中點選某一個按鈕,將父頁面中的iframe隱藏,可以通過window.parent.document.getElementById(iframe的id)來獲取這個iframe,然後將其display屬性設定為none即可。或者通過window.parent來呼叫父頁面中的函式來隱藏iframe,在本例中為window.parent.closeM().

如果父頁面呼叫子頁面的函式或是變數,可以通過ifr_name.window.closeM()來呼叫子頁面的函式。

注:ifr_name為本例中iframe的name,closeM為本例中的函式名稱