需要一些关于使用纯 Javascript 访问 IFrame 的建议。
上下文: 我有一个 JS 脚本“A.JS”,其中包含函数“Func1”。在页面中,该函数在 IFrame 之前调用,如下所示
<script> A.Func1();</script>
<iframe src='xyz.com' title='Hello' type='portlet.iframe' > </iframe>
请注意,这个 IFrame 是随机生成的,因此我在运行时不知道它的 ID 和名称。因此,我访问它的唯一方法是获取 IFrame 数组的句柄并循环遍历每个 IFrame,直到通过其标题识别出正确的 IFrame。
另请注意,JS 函数调用位于 IFrame 之前/之上。
现在在我的函数Func1()
中,我的代码如下。我试图获取正确的 IFrame 的句柄,但下面的所有方法都返回 0 长度的数组。我暂停并在 chrome 版本 29 中看到这一点。实际上,最后一个数组 iframeNodesAll4
显示“Windows”作为值!
var iframeNodesAll1 = document.getElementsByTagName("iframe");
var iframeNodesAll2 = window.parent.document.getElementsByTagName("iframe");
var iframeNodesAll3 = window.document.getElementsByTagName("iframe");
var iframeNodesAll4 = window.frames;
那么我在这里错过了什么?是因为脚本在 IFrame 之前被调用/加载吗?
谢谢!
最佳答案
Is it because the script is being called/loaded before the IFrame?
是的,我相信这是你的问题,尝试将函数调用移到 iframe 之后,看看会发生什么
编辑
或者,您可以等到页面加载后再运行该函数:
<script>
window.onload = function() {
A.func1();
}
</script>
关于javascript - 访问 IFrame 和元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18363418/