JavaScript 弹出子窗体并返回结果到父窗体的实现代

思路:用window.showModalDialog方法获取到弹出子窗体的引用,再在子页面用window.returnValue="***"来返回结果。

示例代码:(用jQuery简化实现)

父页面: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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>父页面</title> <mce:script language="javascript"><!-- function showmodal() { var strReturn = window.showModalDialog("son.html",null,"dialogWidth:800px;dialogHeight:600px;help:no;status:no"); var s="您选择了:"; for(var i=0;i<strReturn.length;i++) { s+=strReturn[i]+","; } alert(s); } // --></mce:script> </body> </html>

子页面 son.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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>子窗体</title> <mce:script type="text/javascript" src="https://www.jb51.net/jquery-1.4.2.min.js" mce_src="https://www.jb51.net/jquery-1.4.2.min.js"></mce:script> <mce:script type="text/javascript"><!-- var result; $(function(){ $("#send").click(function(){ var result=new Array(); $("[name=a]:checkbox:checked").each(function(){ result.push($(this).val()); }); window.returnValue=result; window.close(); }); }); // --></mce:script> </head> <body> <p> <input type="checkbox" value="苹果" />苹果 <input type="checkbox" value="橘子" />橘子 <input type="checkbox" value="香蕉" />香蕉 <INPUT type="button" value="提交" /> </p> </body> </html>

总结:

 参数传递:

1.   要想对话框传递参数,是通过vArguments来进行传递的。类型不限制,对于字符串类型,最大为4096个字符。也可以传递对象,例如:
-------------------------------

parent.htm

<script> var obj = new Object(); obj.name="51js"; window.showModalDialog("son.htm",obj,"dialogWidth=200px;dialogHeight=100px"); </script>

son.htm

<script> var obj = window.dialogArguments alert("您传递的参数为:" + obj.name) </script>

2.   可以通过window.returnValue向打开对话框的窗口返回信息,当然也可以是对象。例如:

parent.htm

<script> str =window.showModalDialog("son.htm",,"dialogWidth=200px;dialogHeight=100px"); alert(str); </script>

son.htm

<script> window.returnValue="http://blog.csdn.net/a497785609"; </script>

扩展:

在.net中,可以通过这种方式来实现AJAX效果。当子页面传递所要选择的参数后,父页面可以实现ICallbackEventHandler接口,直接将获取到的值传回服务器端。或者用UpdatePanel的Load事件来扑捉到传递过来的参数,从而继续进行服务器端处理。

以上这篇JavaScript 弹出子窗体并返回结果到父窗体的实现代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzpzdy.html