一直想做个类似mini ui中的弹出层效果:能够传递参数,能够返回值。传递参数比较容易,后来卡在返回值问题上,看了mini ui 的实现,原来contentwindow属性来实现返回值(parent和openr也可以实现父子窗口的相互操作, javascript原生代码也有能够实现类似功能的方法:showmodaldialog)。
原始代码如下:
parent.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>全面兼容的Iframe 与父页面交互操作</title>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<script type="text/javascript" src="jquery.1.3.2.js"></script>
<script type="text/javascript">
$(function(){
document.getElementById('childframe').contentWindow.childFunction();
});
</script>
</head>
<body>
<div style="width: 100%; height: 250px;">
<iframe id="childframe" name="myiframeA" src="http://localhost:8080/b.html" scrolling="no" frameborder="0"></iframe>
</div>
</body>
</html>
child.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>全面兼容的Iframe 与父页面交互操作</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript" type="text/javascript">
function childFunction() {
alert("childframe");
}
</script>
</head>
<body>
</body>
</html>
这是的效果是控制台一直报错:childFunction is not a function .这时我一直以为是浏览器兼容的问题。但是查了资料都说contentwindow属性是所有浏览器都兼容的,各个浏览器调试这个对象也是兼容的。后来在网上看到一个博客说要在onload 方法中才能调用iframe中的方法。后来试结果可以。
parent.html修改为:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>全面兼容的Iframe 与父页面交互操作</title>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<script type="text/javascript" src="jquery.1.3.2.js"></script>
<script type="text/javascript">
function init() {
document.getElementById('childframe').contentWindow.childFunction();
}
</script>
</head>
<body onload="init()">
<div style="width: 100%; height: 250px;">
<iframe id="childframe" name="myiframeA" src="http://localhost:8080/b.html" scrolling="no" frameborder="0"></iframe>
</div>
</body>
</html>
为什么会产生这种原因?原博主解释大概是iframe中的属性(childFunction())还没有加载完,详情查看onload方法和$.ready();的执行先后和时间。自己也验证了一下:在即将执行前断点调试图:
直接调用时:
onload方法调用:
直接调用不能识别childFunction方法,说明这是iframe没有解析完成或找不到,使用onload方法时childFunction() 为undefine 说明方法已经申明了,没有赋值。这和上面的观点相符合。
父窗口能够调用到子窗口的方法,能够作为弹出层的返回值功能基础。
昨天没写完,今天把后面不起来。
最开始测试的时候用的是Firefox 后来用其他浏览器测试发现不兼容,准确的说也不是兼容问题,在iframe中嵌入b.htmla存在跨域问题,在chrome和360中都存在。
我的解决办法是把两个文件(a.html ,b.html)放在tomcat的根目录下面。测试可以兼容所有的浏览器。
在客户端解决跨域访问方式:
http://blog.youkuaiyun.com/fdipzone/article/details/17619673
ps:如有错误请各位大神斧正。