130
技術社區[雲棲]
JavaScript 彈出子窗體並返回結果到父窗體
思路:用window.showModalDialog方法獲取到彈出子窗體的引用,再在子頁麵用window.returnValue="***"來返回結果。
示例代碼:(用jQuery簡化實現)
父頁麵:parent.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="https://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" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="https://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="jquery-1.4.2.min.js" mce_src="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" name="a" value="蘋果" />蘋果 <input type="checkbox" name="a" value="橘子" />橘子 <input type="checkbox" name="a" 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="https://blog.csdn.net/a497785609";
</script>
擴展:
在.net中,可以通過這種方式來實現AJAX效果。當子頁麵傳遞所要選擇的參數後,父頁麵可以實現ICallbackEventHandler接口,直接將獲取到的值傳回服務器端。或者用UpdatePanel的Load事件來撲捉到傳遞過來的參數,從而繼續進行服務器端處理。
最後更新:2017-04-02 06:51:24