项目中通过iframe内嵌了一个子页面,子页面定义了一些全局变量,父页面需要获取子页面的全局变量,做了一些测试(我的环境IE10和Firefox32.0.3),得出如下结论:
IE下: window.frames['iPage'].变量名
火狐下:window.frames['iPage'].contentWindow.变量名
IE&火狐下:document.getElementById('iPage').contentWindow.变量名
具体原因没有深究,今天在调试一个iframe例子的时候发现了问题所在(iframe没有定义name属性),下面做了一个实例
父页面 parent.html
<html>
<script>
function test(){
var obj1=document.getElementById("myframe");//获得对应iframe的HTMLIFrameElement对象,可以获取iframe相关属性
alert(obj1.src);
/*情况一:iframe定义了name="myframe"的情况 IE和火狐兼容*/
var obj2=window.frames["myframe"];//获得对应iframe的window对象
alert(obj2.company);
alert(obj2.document.myform.username.value);
alert(obj1.contentWindow==obj2);//true,可见document.getElementById("myframe").contentWindow与document.frames["myframe"]都是指向iframe对应的window对象
alert(obj1.contentWindow.document.myform.username.value);
/*情况二:iframe没有定义name="myframe"的情况,情况如同文章最开始所描述
var obj2=window.frames["myframe"];//获得对应iframe的window对象
alert(obj2.company);//IE下正确,火狐下错误
alert(obj2.contentWindow.company);//IE下错误,火狐下正确
alert(obj2.contentWindow.document.myform.username.value);//IE下错误,火狐下正确
alert(obj1==obj2);//true,可见document.getElementById("myframe")与document.frames["myframe"]都是指向iframe对应的HTMLIFrameElement对象
*/
}
</script>
<body onload="test()">
<iframe id="myframe" name="myframe" src="child.html" frameborder="3" style="width:300;height:200;border-width:1;border-color:red;border-style:solid"></iframe>
</body>
</html>
子页面 child.html
<html>
<script>
var company="cppei";
</script>
<body>
<form name="myform">
用户名:<input type="text" name="username" value="test" />
</form>
</body>
</html>
最后得出的结论是:要在父页面访问iframe内子页面的全局变量,
1、在iframe 定义了name属性的情况下
IE&火狐下: window.frames['iPage'].变量名
IE&火狐下:document.getElementById('iPage').contentWindow.变量名
因为此时 window.frames['iPage']==document.getElementById('iPage').contentWindow
2、在iframe 没有定义name属性的情况下
IE下: window.frames['iPage'].变量名
火狐下:window.frames['iPage'].contentWindow.变量名
IE&火狐下:document.getElementById('iPage').contentWindow.变量名
因为此时火狐下window.frames['iPage']==document.getElementById('iPage'),所以要加上contentWindow来访问变量
所以定义iframe时还是最好加上name属性吧