2014-12-05 101 views
0

我的設置,我有無法控制之內的工作:Javascript/jQuery - 如何從多個iframe中獲取父元素?

父 - > Iframe-> Iframe->我的文檔

如何訪問是在父從我的文檔中的一個元素?

這些都在同一個域上,所以沒有跨域問題。我可以直接使用JS或jQuery來做到這一點。

我一直在四處搜尋,但還沒有找到任何有人試圖通過多個iframe從底部訪問頂部元素的任何示例!

的解決方案,如果任何人遇到這樣的:

var p = $("#Viewport",window.top.document); 
alert(p.attr('name')); 
+0

如果只有一個iframe,您將如何訪問包含在父級中的元素? – Kolban 2014-12-05 00:42:42

回答

0

我相信你將能夠通過window.parent訪問此,作爲這樣的:

window.parent.document.getElementById('target-element'); 
+0

我收到一個空錯誤。示例代碼: 視口在父: '<元ID = 「視口」 名稱= 「視口」>' 以我的iframe '變種P = window.parent.document.getElementById( '視口');' 'alert(p.getAttribute(「name」));' – 2014-12-05 01:00:33

0

只需使用window.top,如:

console.log(top.document.getElementById('someInputId').value); 

請注意window in impl icit,所以你可以離開它。當然,您必須將'someInputId'更改爲首頁上的輸入ID,以查看這是否有效。如果您針對不是輸入的元素進行測試,請使用.innerHTML而不是.value

+0

錯誤:top.getElementById不是函數。 – 2014-12-05 17:24:13

+0

我忽略了'top'窗口的'document'屬性。固定。 – PHPglue 2014-12-06 00:05:08