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):
- <!DOCTYPE html >
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>parent</title>
- </head>
- <body>
- <input type="button" value="call child" onclick="callChild()"/>
- <iframe name="child" src="child.html" ></iframe>
- <script>
- function parentFunction() {
- alert('function in parent');
- }
- function callChild() {
- //child 為iframe的name屬性值,不能為id,因為在FireFox下id不能獲取iframe對象
- child.window.childFunction();
- }
- </script>
- </body>
- </html>
子頁面(iframe頁面,child.html):
- <!DOCTYPE html >
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>child</title>
- </head>
- <body>
- <input type="button" value="call parent" onclick="callParent()"/>
- <script>
- function childFunction() {
- alert('function in child');
- }
- function callParent() {
- parent.parentFunction();
- }
- </script>
- </body>
- </html>