如何从文档对象访问窗口对象

How to access the window object from the document object

本文关键字:对象 访问 窗口 文档      更新时间:2023-09-26

是否可以直接从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

根据MDN文档,您应该已经获得了window.frames[0]的窗口。如果需要实际的文档,则需要获取实际的框架元素并深入到文档中。

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

注意:我相信contentWindow在Safari的早期版本(3.0之前的IIRC)中不支持