Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么我可以访问iFrame而不能访问其内容?_Javascript_Jquery_Iframe - Fatal编程技术网

Javascript 为什么我可以访问iFrame而不能访问其内容?

Javascript 为什么我可以访问iFrame而不能访问其内容?,javascript,jquery,iframe,Javascript,Jquery,Iframe,我试图访问iFrame的内容,但我一无所获 我有这个: that.findGadget = $.fn.findGadget = function (root) { var root = root || this; if (root[0].tagName === "IFRAME") { root = root[0].contentDocument || root[0].contentWindow.document; } console.log(root

我试图访问iFrame的内容,但我一无所获

我有这个:

that.findGadget = $.fn.findGadget = function (root) {
    var root = root || this;
    if (root[0].tagName === "IFRAME") {
       root = root[0].contentDocument || root[0].contentWindow.document;
    }
    console.log(root); 
})

我在iFrame本身上调用函数,如下所示:

// options is my configuration object with id/src/...
var newHTML = document.createElement("iframe");
newHTML.setAttribute("src", options.src);
newHTML.setAttribute("frameborder", 0);
newHTML.setAttribute("data-id", options.id);
// add iFrame to page
// options.parent is a $(element)
newParentElement = options.parent.parent()[0];
options.parent.replaceWith( newHTML );

// select
var newRootElement = newParentElement.querySelectorAll(
    '[data-id="'+options.id+'"]'
  );
// calling on $('iframe')
$( newRootElement[0] ).findGadget();
...
findGadget
中的if语句工作正常,因此
root
被设置为iFrame的
document
。然而,我被困在那里,因为我正在尝试的其他一切:

root.body
root.body.innerHTML
$(root).find('div');
$('iframe').contents();
未定义或选择器为空

问题
如何正确访问iFrame的元素?问题可能是内容尚未加载?我正在使用localstorage,因此所有文件都来自同一个“域”

谢谢你的帮助

考虑以下几点:

1) 我建议在加载iframe时启动
findGadget()
函数。您可以通过在iframe的页面本身中调用它,或者通过放置整个
$(newRootElement[0]).findGadget()来实现这一点进入

$(newRootElement[0]).ready(function (){
    // here
});

2) 我建议只使用
contentWindow
,因为它与所有浏览器完全兼容(已测试)。

对,您需要等待iframe内容加载完毕。使用jQuery:

$('iframe').load(function () {                        
    // access the iframe content
});

iframe是否已完全加载?它在同一个域中吗?同一个域:是的。如何检查它是否已加载?什么是
options.src
?您提到的本地存储意味着它可能是一个
数据:
URI。@Quentin:类似于“files/foo.html”的内容,您必须先检查iframe是否已加载,然后才能访问其内容
加载
是为我做的。因为现在
这个
是包含内容的iframe。谢谢