1. 程式人生 > >javascript 視窗互動

javascript 視窗互動

1。父視窗傳遞資訊給子視窗
  看程式碼例項:
  <script language=javascript>
  function outPut()
  {
  //獲取父視窗的文字資訊賦值給text
  var text = document.abc.text.value;
  //開啟子視窗,並且把操作控制代碼賦值給win變數,以下所有操作都是針對win物件的
  var win = window.open("","mywin", "menubar=no,width=400,height=100,resizeable=yes");
  //輸出基本資訊
  win.document.writeln("<title>輸出結果</title>");
  win.document.writeln("你的資訊是:<p>");
  //輸出從父視窗獲取的資訊
  win.document.writeln(text);
  win.document.close();
  win.focus();
  }
  </script>
  <form name=abc method=post>
  <input type=text name=text size=50>
  //呼叫上面的函式
  <input type=button value=提交 onClick="outPut()">
  </form>
  2。子視窗傳遞引數給父視窗
  我們對上面的程式碼進行改造:
  <script language=javascript>
  function outPut()
  {
  var text = document.abc.text.value;
  var win = window.open("","mywin", "menubar=no,width=400,height=100,resizeable=yes");
  win.document.writeln("<title>輸出結果</title>");
  win.document.writeln("你的資訊是:<p>");
  win.document.writeln(text);
  win.document.writeln("<input type=text name=child value=子視窗資訊>");
  //對子視窗本身操作,使用self物件,對父視窗操作使用opener物件,這是關鍵
  //把子視窗中表單的值回傳給父視窗,取代父視窗表單以前的值,然後關閉子視窗
  win.document.writeln("<input type=button value=關閉自己 onClick='window.opener.abc.text.value=self.child.value;self.close()'>");
  //可以控制關閉父視窗
  win.document.writeln("<input type=button value=關閉父視窗 onClick='window.opener.opener=null;window.opener.close()'>");
  //重新整理父視窗
  win.document.writeln("<input type=button value=重新整理父視窗 onClick='window.opener.location.reload()'>");
  win.document.close();
  win.focus();
  }
  </script>
  <form name=abc method=post>
  <input type=text name=text size=50>
  <input type=button value=提交 onClick="outPut()">
  </form>
  3。不是同頁面的子視窗和父視窗互動
  假設我們涉及到外部程式,比如php、asp等等,那麼我們處理的可能是兩個頁面,比如,上傳功能,我們就是需要開啟一個新頁面,然後再把新頁面中的值傳遞給父頁面。
  區域性程式碼例項:
  <input type="input" value="" name="input_tag" id = "input_tag" onKeyUp="clearPreTagStyle()" size="40">
  <input type="hidden" value="0" name="tagid" id="tagid">
  <input type="button" value="標籤" onclick="popUpWindow('tag.php?tag='+escape(document.tryst_form.input_tag.value))">
  以上是父視窗的部分程式碼,裡面的popUpWindow是封裝好的window.open函式,所以理解面面的tag.php是另外一個頁面就可以,我們需要把當前表單中的值提交給tag.php頁面去處理。
  tag.php部分程式碼:
  查詢標籤結果:
  <a href="#" name="tag_1">生活</a><a href="#" onclick="opener.document.tryst_form.input_tag.value = document.tag_1.innerHTML">加入該標籤</a>
  <a href="#" name="tag_2">生活秀</a><a href="#" onclick="opener.document.tryst_form.input_tag.value = document.tag_2.innerHTML">加入該標籤</a>
  這個就是我們的子視窗,我們要把tag_1和 tag_2返回到子視窗中,雖然他們不是同一個頁面。這裡有個知識點,就是我們如何獲取連線中的值,我們使用innerHTML屬性:document.tag_2.innerHTML 這個就是我們獲取了tag_2的值“生活秀”,我們也能使用其他方法獲取,比如:document.all.tag_2.innerHTML,或者 this.innerHTML就是指本身的連結的值。
  訪問父視窗也是使用opener物件來處理:opener.document.tryst_form.input_tag.value,就能夠改變父視窗的值。

文章出處:飛諾網(www.firnow.com):http://dev.firnow.com/course/1_web/javascript/jsjs/20091202/183886.html