父頁面調用子頁面js的方法


iframe子頁面調用父頁面javascript函數的方法
今天遇到一個iframe子頁面調用父頁面js函數的需求,解決起來很簡單,但是在chrome瀏覽器遇到一點小問題。順便寫一下iframe的父頁面調用子頁面javascript函數的方法吧,備用!

1、iframe子頁面調用 父頁面js函數

子頁面調用父頁面函數只需要寫上window.praent就可以了。比如調用a()函數,就寫成:

window.praent.a();

但是我在chrome瀏覽器下卻發現此方法無效了!查了半天才了解,在chrome 5+中,window.parent無法在file://協議中運行,但是發布了之后http://協議下是可以運行的。此方法支持ie、firefox瀏覽器。

2、iframe父頁面調用 子頁面js函數

這個就稍微復雜一些,下面的方法支持ie和firefox瀏覽器:

document.getElementById('ifrtest').contentWindow.b();

注:ifrtest是iframe框架的id,b()為子頁面js函數。contentWindow屬性是指定的frame或者iframe所在的window對象,IE下可以省略。

父頁面(parent.html):

  1. <!DOCTYPE html >  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  5. <title>parent</title>  
  6. </head>  
  7.   
  8. <body>  
  9. <input type="button" value="call child" onclick="callChild()"/>  
  10. <iframe name="child" src="child.html" ></iframe>  
  11.   
  12. <script>  
  13.   
  14. function parentFunction() {  
  15.     alert('function in parent');  
  16. }  
  17.   
  18. function callChild() {  
  19.     //child 為iframe的name屬性值,不能為id,因為在FireFox下id不能獲取iframe對象  
  20.     child.window.childFunction();  
  21. }  
  22.   
  23. </script>  
  24.   
  25. </body>  
  26. </html>  

子頁面(iframe頁面,child.html):

  1. <!DOCTYPE html >  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  5. <title>child</title>  
  6. </head>  
  7.   
  8. <body>  
  9. <input type="button" value="call parent" onclick="callParent()"/>  
  10.   
  11. <script>  
  12.   
  13. function childFunction() {  
  14.     alert('function in child');  
  15. }  
  16.   
  17. function callParent() {  
  18.     parent.parentFunction();  
  19. }  
  20.   
  21. </script>  
  22.   
  23. </body>  
  24. </html>  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM