JavaScript 获取 iframe 内页面元素值的方法

作者:竹影时间:2026-10-27 22:35:36浏览:416

本文介绍如何在 JavaScript 中获取 iframe 内部页面的元素值,重点解决 IE 与 Firefox 浏览器的兼容性问题。通过判断 document.frames 对象存在与否,分别采用不同的 DOM 访问路径,并提供完整的 a.html 与 b.html 示例代码供参考。

不同浏览器的 iframe 访问方法

在 IE 浏览器中,可以通过 document.frames 集合直接访问 iframe 文档对象。具体语法为:document.frames['myFrame'].document.getElementById('test').value; 其中 'myFrame' 是 iframe 的 ID,'test' 是目标元素的 ID。

在 Firefox 浏览器中,需通过 contentWindow 属性获取 iframe 的窗口对象,再访问其 document。具体语法为:document.getElementById('myFrame').contentWindow.document.getElementById('test').value; 这里同样假设 iframe ID 为 'myFrame',目标元素 ID 为 'test'。

为了实现跨浏览器兼容,可以结合上述两种方法,通过检测 document.frames 是否存在来区分浏览器类型,从而执行相应的获取逻辑。

以下是兼容 IE 和 Firefox 的 JavaScript 函数实现代码:

function getValue(){
var tmp = '';
if(document.frames){
tmp += 'ie哥说:';
tmp += document.frames['myFrame'].document.getElementById('test').value;
}else{
tmp = document.getElementById('myFrame').contentWindow.document.getElementById('test').value;
         }
alert(tmp);
    }

兼容 IE 与 Firefox 的完整代码示例

以下是完整的 HTML 页面示例,包含主页面 a.html 和 iframe 页面 b.html 的代码。


a.html 页面中的代码


a.html 的完整 HTML 结构如下,包含一个 iframe 和一个触发获取值的按钮:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>
javascript 获取iframe里页面中元素的值 测试
</title>
</head>
<body>
<iframe id="myFrame" src='b.html' style="width:300px;height: 50px;"></iframe>
<input type="button" id="btn" onclick="getValue()" value="test" >
<script type="text/javascript">
function getValue(){
var tmp = '';
if(document.frames){
tmp += 'ie哥说:';
tmp += document.frames['myFrame'].document.getElementById('test').value;
}else{
tmp = document.getElementById('myFrame').contentWindow.document.getElementById('test').value;
                            }
alert(tmp);
                        }
</script>
</body>
</html>

iframe 内部页面 b.html 结构

b.html 页面中的代码


b.html 是 iframe 加载的页面,包含一个文本输入框,其 ID 为 'test',用于展示获取值的来源:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>
我是 iframe内的页面
</title>
</head>
<body>
<input type='text' id="test" value='欢迎访问:justflyhigh.com'>
</body>
</html>
作者最新文章