获取嵌套在 JavaScript 中的 Frame 内的 iframe 内的元素值?

2024-03-22

我的 php 主页面有 2 个框架。第二个框架内有 iframe。 我想从第一帧访问 iframe 文档上元素的值。

我尝试这样:

var frame1 = parent.frames[1];
var frame2 = frame1.document.getElementsByTagName('iframe')[0];
var eleValue =frame2.contentWindow.document.getElementById("MyElement").value;

但我没有收到任何价值,尽管它在那里。

var frame1 = parent.frames[1];
alert(frame1.name);
var frame2 = frame1.document.getElementsByTagName('iframe')[0];
alert(frame2.name);
var txtClinic = frame1.document.getElementsByTagName('iframe')[0].contentDocument.getElementById("clinicFlag");

最后一行代码不返回任何控制对象。


这是评论中链接的我的答案的修改片段。函数返回window(i) 框架的对象id通过(id), or null,如果(i)frame没有找到。仅当所有(i)frames 位于同一域中。还ids 给予(i)frame元素在整个过程中必须是唯一的all涉及窗口结构的文件。

function searchFrame(id) {                                     // id = the id of the wanted (i)frame
    var result = null,                                         // Stores the result
        search = function (iframes) {                          // Recursively called function
            var n;                                             // General loop counter
            for (n = 0; n < iframes.length; n++) {             // Iterate through all passed windows in (i)frames
                if (iframes[n].frameElement.id === id) {       // Check the id of the (i)frame
                    result = iframes[n];                       // If found the wanted id, store the window to result
                }
                if (!result && iframes[n].frames.length > 0) { // Check if result not found and current window has (i)frames
                    search(iframes[n].frames);                 // Call search again, pass the windows in current window
                }
            }
        };
    search(window.top.frames);                                  // Start searching from the topmost window
    return result;                                              // Returns the wanted window if found, null otherwise
}

这个函数可以找到一个frame or iframe与过去的id无论它放置在窗口结构中的哪个位置。该函数还可以在任何窗口中放置和调用。我会将其放在主页上(作为全局页面)。如果子窗口需要该方法,只需调用top.searchFrame(...).

代替ids, also name可以使用,只要它们也是唯一的。在这种情况下id报到searchFrame()需要编辑为name check.

对于你的情况,首先你需要给出一个id到目标iframe,那么您可以使用如下代码:

var txtClinic = searchFrame('IFRAME_ID').document.getElementById('clinicFlag');

上面的方法对于获取单个引用可能有点大材小用,但是如果您必须在不同窗口中多次获取这些跨窗口引用,那么它非常有帮助。

你的具体任务可以这样完成:

var txtClinic = parent.frames[1].frames[0].document.getElementById('clinicFlag');

name(i)frame也很方便使用frames收藏。您可以使用名称来代替索引。始终从主页开始链接引用,即从top。例如:

var iframeWin = top.frames['frame2'].frames['iframe1'];

有用的阅读:

窗口顶部 https://developer.mozilla.org/en-US/docs/Web/API/Window.top
窗口.frameElement https://developer.mozilla.org/en-US/docs/Web/API/Window.frameElement
窗框 https://developer.mozilla.org/en-US/docs/Web/API/Window.frames

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

获取嵌套在 JavaScript 中的 Frame 内的 iframe 内的元素值? 的相关文章