hi,欢迎访问本站!
当前位置: 首页学习笔记正文

html如何获取iframe中嵌套的页面元素值,在javascript中嵌套在Frame内的iframe中获取元素值?...

用户投稿 学习笔记 14阅读

我主要的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");

最后一行代码不返回任何控件对象.

解决方法:

这是我在评论中链接的修改后的片段.函数返回id传递(id)的(i)帧的window对象,如果未找到(i)帧,则返回null.如果所有(i)帧都在同一个域中,则此方法有效.给予(i)框架元素的ID在窗口结构中涉及的所有文档中必须是唯一的.

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

}

此函数可以找到具有传递的id的帧或iframe,无论它放在窗口结构中的哪个位置.此功能也可以在任何窗口中放置和调用.我把它放到主页面(作为全局).如果在子窗口中需要该方法,只需使用top.searchFrame(…)调用.

除了id之外,还可以使用名称,只要它们也是唯一的.在这种情况下,需要编辑searchFrame()中的id检查以进行名称检查.

在您的情况下,首先您需要为目标iframe提供一个id,然后您可以使用代码,例如:

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

上面的方法可能有点过分来获得单个引用,但如果你必须在不同的窗口中多次获得这些跨窗口引用,它会非常有用.

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

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

(i)帧的名称也可以方便地用于帧集合.而不是索引,您可以使用名称.只需始终从主页开始链接参考,即从顶部开始.例如:

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

有用的阅读:

标签:getelementbyid,javascript,iframe,frame

来源: https://codeday.me/bug/20190925/1816628.html

标签:
声明:无特别说明,转载请标明本文来源!
发布评论
正文 取消