2011-09-27 87 views
2

是否可以直接从Javascript中的文档对象访问窗口对象?如何从文档对象访问窗口对象

例如:

// window.frames[0] returns the document object of the first frame or iframe found on the page 
myFunc(window.frames[0]); 

function myFunc(doc) { 
    // I want to do something along these lines: 
    var wnd = doc.getWindow(); 
    alert("Found frame: " + wnd.name); 
    for (var i=0; i<wnd.frames.length; i++) { 
    myFunc(wnd.frames[i]); 
    } 
} 

我不能使用jQuery这个,对不起。

回答

0

根据MDN documentation您应该已经开始使用window.frames[0]了。如果您想要实际的文档,您需要抓取实际的框架元素并挖掘文档。

var firstFrame = document.getElementsByTagName("iframe")[ 0 ]; 
firstFrame.contentWindow; // The window 
firstFrame.contentWindow.document; // The document 

注:我相信contentWindow是不是在Safari(预3.0 IIRC)

+0

的非常早期的版本支持不幸的是并非如此。尝试使用'contentWindow'在我的问题中给出的示例代码,您会发现它不起作用,当然不是在所有浏览器中。 –

+0

根据MDN文档@NickBrunt,'windows.frames [0]'的结果应该是'contentWindow'。 'window.frames [0]'和'document.getElementsByTagName(“iframe”)[0]' – JaredPar

+0

之间有区别*应该发生什么和发生什么有很大的区别。自己尝试一下。 –