window.open与window.showModalDialog中主页面与从页面间的通信(原创) 中庸

          由于前台的蹩脚,每次遇到问题都要查询一下,这不刚又遇到点小问题,查了一下 ,把查询结果分享一下(简单的很哦,高手和中级就不要看了)

    一,理论

                window.open与window.showModalDialog,前者用于打开一个新的浏览器窗口或查找一个已命名的窗口,后者用来创建一个显示HTML内容的模态对话框,由于

         对话框,因此它并没有一般用window.open()打开的窗口的所有属性。

                 主页面与从页面之间能通信包括:主页面传值给从页面和从页面传值给主页面,由于前者比较简单,故本文只说后者

  二, 示例         

            1. window.showModalDialog示例

                  zhu.html代码如下

<html>
<head>
<title>对话框小示例</title>
</head>
<body>
<center>
<form name="form1">
<br />
<h1>单击按钮,选择你喜欢的颜色</h1>
<br />
<input type="button" value="选择颜色" onClick="Selectcolor()" />
<br />
<br />
<input type="text" name="Textbox" size="20" />
<br />
</form>
</center>
</body>
<script language="javascript">
  function Selectcolor()
  {
    document.form1.Textbox.value=window.showModalDialog("cong.html");
  }
</script>
</html>

cong.html代码如下

<html>
<head>
<title>测试对话框</title>
</head>
<body>
<center>
<form name="form1">
<br />
<br />
<h1>选择您喜欢的颜色</h1>
<br />
<table bordercolor="#00FFFF" width="200">
  <tr>
     <td>
    <input type="radio" name="RadioButtons" onclick="radio1Clicked()"/>红
   </td>
   </tr>
   <tr>
      <td>
     <input type="radio" name="RadioButtons" onClick="radio2Clicked()">橙
      </td>
 </tr>
   </table>
    <br />
 <input type="button" value="确认" onClick="OKButton()"/>
 <input type="button" value="取消"  onClick="CancelButton()"/>
 </form>
</center>
</body>
<script language="javascript">
  var selectedcolor="没有选择";
   function radio1Clicked()
   {
     selectedcolor="红";
   }
   function radio2Clicked()
   {
     selectedcolor="橙";
   }
   function OKButton()
   {
     window.returnValue="您选择的颜色为:"+selectedcolor;
     window.close();
   }
   function CancelButton()
   {
     window.returnValue="您没有做出选择";
     window.close();
   }
   </script>
  </html>

            2. window.open()示例   

                     只需将zhu.html红色部分改为:window.open("cong.html");和cong.html红色部分改为:window.opener.document.getElementById("TextBox").value
                     ="您选择的颜色为:"+selectedcolor;即可

            总结:

                    1.window.showModalDialog("cong.htm")的返回值为:cong.html本页面的window.returnValue,故只需在cong.html页面对window.returnValue赋值,

                       然后在zhu.html页面进行调用返回值即可

                   2.window.open("cong.html")返回值为:打开窗口的引用(失败返回null),window.opener是指调用window.open方法的窗口,即调用cong.html窗口的窗口, 

                      即:zhu.html,从而完成对主窗口中控件的访问
    

原文地址:https://www.cnblogs.com/liangjie/p/1956239.html