我想使用jQuery在iframe中操纵HTML。

我想我可以通过将jQuery函数的上下文设置为iframe的文档来实现这一点,比如:

$(function(){ //document ready
    $('some selector', frames['nameOfMyIframe'].document).doStuff()
});

然而,这似乎不起作用。一点检查显示,帧['nameOfMyIframe']中的变量未定义,除非等待一段时间加载iframe。然而,当iframe加载时,变量是不可访问的(我得到了拒绝权限的类型错误)。

有人知道这方面的工作吗?


当前回答

Use

iframe.contentWindow.document

而不是

iframe.contentDocument

其他回答

Use

iframe.contentWindow.document

而不是

iframe.contentDocument

您是否使用jQuery的内置就绪函数尝试过经典的等待加载完成的方法?

$(document).ready(function() {
    $('some selector', frames['nameOfMyIframe'].document).doStuff()
} );

K

我觉得这样更干净:

var $iframe = $("#iframeID").contents();
$iframe.find('selector');

要获得更高的鲁棒性:

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

and

...
var frame_win = getIframeWindow( frames['nameOfMyIframe'] );

if (frame_win) {
  $(frame_win.contentDocument || frame_win.document).find('some selector').doStuff();
  ...
}
...

您需要将事件附加到iframe的onload处理程序,并在其中执行js,以便在访问iframe之前确保iframe已完成加载。

$().ready(function () {
    $("#iframeID").ready(function () { //The function below executes once the iframe has finished loading
        $('some selector', frames['nameOfMyIframe'].document).doStuff();
    });
};

以上内容将解决“尚未加载”的问题,但关于权限,如果您在iframe中加载来自不同域的页面,则由于安全限制,您将无法访问该页面。