我正在尝试访问 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 的元素?问题可能是内容尚未加载吗?我正在使用本地存储,因此所有文件都来自同一个“域”。
感谢您的帮助!
最佳答案
对,您需要等待 iframe 内容加载完毕。使用 jQuery:
$('iframe').load(function () {
// access the iframe content
});
关于javascript - 为什么我可以访问 iFrame 但不能访问其内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16673325/