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

use*_*775 2 javascript iframe frame getelementbyid

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

我尝试这样:

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

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

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");
Run Code Online (Sandbox Code Playgroud)

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

Tee*_*emu 5

这是评论中链接的我的答案的修改片段。函数通过传递 ( ) 或 ,返回window(i) 帧的对象,如果未找到。仅当所有s 都在同一域中时,此方法才有效。此外,元素在窗口结构中涉及的所有文档中必须是唯一的。ididnull(i)frame(i)frameid(i)frame

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
}
Run Code Online (Sandbox Code Playgroud)

该函数可以通过传递的frame或来查找或,无论它放置在窗口结构中的哪个位置。该函数还可以在任何窗口中放置和调用。我会将其放在主页上(作为全局页面)。如果子窗口需要该方法,只需用 调用即可。iframeidtop.searchFrame(...)

除了 s 之外id,也name可以使用 s,只要它们也是唯一的。在这种情况下,需要编辑id签入以进行检查。searchFrame()name

id在您的情况下,首先您需要向 target提供 an iframe,然后您可以使用如下代码:

var txtClinic = searchFrame('IFRAME_ID').document.getElementById('clinicFlag');
Run Code Online (Sandbox Code Playgroud)

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

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

var txtClinic = parent.frames[1].frames[0].document.getElementById('clinicFlag');
Run Code Online (Sandbox Code Playgroud)

name的 s(i)frame也可以方便地与集合一起使用frames。您可以使用名称来代替索引。始终从主页(即从top. 例如:

var iframeWin = top.frames['frame2'].frames['iframe1'];
Run Code Online (Sandbox Code Playgroud)

有用的阅读:

window.top
window.frameElement
window.frames