2012-03-16 66 views
0

我想從另一個框架調用一個函數。但是,當我使用「document.getElementById(frame_id))」它找不到。在另一層的其他iframe中調用一個函數

我檢查了文檔的innerHTML輸出是什麼,並且我需要定位的iframe是另一個iframe中的1層。

在主iframe中我使用: 的document.getElementById( '玩家')),但它retuns:空

我需要去的 「玩家」 的iframe中的 「菜單」 IFRAME ..

這裏是 「主」 I幀頭部代碼:

function callPlayer(frame_id, func, args){ 
    if(!frame_id) return; 
    if(frame_id.id) frame_id = frame_id.id; 
    else if(typeof jQuery != "undefined" && frame_id instanceof jQuery && frame_id.length) frame_id = frame_id.get(0).id; 
    if(!document.getElementById(frame_id)) return; 
    args = args || []; 

    /*Searches the document for the IFRAME with id=frame_id*/ 
    var all_iframes = document.getElementsByTagName("iframe"); 
    for(var i=0, len=all_iframes.length; i<len; i++){ 
     if(all_iframes[i].id == frame_id || all_iframes[i].parentNode.id == frame_id){ 
      /*The index of the IFRAME element equals the index of the iframe in 
      the frames object (<frame> . */ 
      window.frames[i].postMessage(JSON.stringify({ 
       "event": "command", 
       "func": func, 
       "args": args, 
       "id": frame_id 
      }), "*"); 
     } 
    } 
} 

function switchState() 
{ 
    callPlayer('player', 'stopVideo'); 
} 

希望有人理解我的描述..

the HTML in Firebug

+0

等待,爲什麼會出現在iframe的HTML標記? – 2012-03-16 12:22:05

+0

該網站基於KusabaX 0.9.3框架。這是該網站的建立方式,我將無法改變.. – 2012-03-16 12:24:11

+0

@JeffreySweeney,因爲iframe包含有效的HTML文檔,所以iframe的第一個孩子應該始終是HTML。 – tkone 2012-03-16 12:36:19

回答

1

您可以使用

window.parent.document.getElementById("player").contentWindow 

從「主」的iframe爲目標的「玩家」 iframe的window對象,並有調用它的函數。

例如:

window.parent.document.getElementById("player").contentWindow.player_func(); 
+0

window.parent.document.getElementById(「player」)。contentWindow返回null – 2012-03-16 12:53:38

+0

對,我錯過了玩家iframe在菜單iframe中。所以你必須經歷:window.parent.document.getElementById(「menu」)。contentWindow.document.getElementById(「player」)。contentWindow.player_func(); – 2012-03-16 13:09:20

+0

非常感謝! – 2012-03-16 13:14:18

0

您可以使用parent對象來尋址您的 iframe所在的容器。

+1

它看起來像Hagbart正在使用'postMessage'消息一個YouTube網頁,這表明該網頁是在不同的域。因此,「父母」不起作用。 – 2012-03-16 12:25:09

+0

@JeffreySweeney - 你說得對! – mrab 2012-03-16 12:26:56

+0

我正在使用javascript youtube API來嵌入視頻。原因是我想在「主」iframe中有一個按鈕來切換播放器的啓動和停止。它們都在同一個域中。 – 2012-03-16 12:27:35

相關問題