เขียน javascript เล่นกับ popup และ opener
2,356 viewsพอดีต้องเขียน javascript สั้นๆ เป็นตัวอย่างไปให้ programmer อีกท่านที่ไม่ถนัด javascript
เลยคิดว่าน่าจะเอามาเล่าให้ฟัง
การทำงานคือ หน้าต่างหลักมี text field อยู่ พอกดปุ่มจะเปิด popup ขึ้นมาโดยจะมี textarea
เพื่อกรอกข้อมูล พอกดปุ่ม submit ค่าที่อยู่ใน textarea จาก popup จะไปอยู่ใน text field
ตัวหน้าต่างหลัก, แปลงจากขึ้นบรรทัดใหม่เป็น : แทน และ popup ปิดตัวเอง ตามรูป

ขออธิบายส่วนที่น่าสนใจแล้วกันนะครับ
ไฟล์ test.html (หน้าต่างหลัก)
// function นี้มีไว้เพื่อสร้าง popup ให้อยู่กลางจอเสมอ function popUpWindow(URL, N, W, H, S) { // name, width, height, scrollbars var winleft = (screen.width - W) / 2; var winup = (screen.height - H) / 2; winProp = 'width='+W+',height='+H+',left='+winleft+',top=' +winup+',scrollbars='+S+',resizable' + ',status=yes' Win = window.open(URL, N, winProp) if (parseInt(navigator.appVersion) >= 4) { Win.window.focus(); } } function popUpTextArea() { // สั่งสร้าง popup จากการกดปุ่มที่หน้าต่างหลัก popUpWindow('popup_textarea.html','SH1',340,130,'no'); }
ไฟล์ popup_textarea.html
// เมื่อกดปุ่ม Set Value ที่ popup จะอ่านค่าจาก textarea มา // และแปลงจาก \n (ขึ้นบรรทัดใหม่) เป็น : function setContent () { var strContent = document.frmSelect.tbTextArea.value; strContent = replaceString(strContent,'\n',':'); // window.opener ก็คือตัวที่เปิดมันขึ้นมานั่นเอง window.opener.document.frmTest.tbTest.value=strContent; window.close(); } // เอาไว้ replace ข้อความใน string ตามต้องการ function replaceString (strString,strFind,strReplace) { while (strString.indexOf(strFind)>-1) { intPosition= strString.indexOf(strFind); strString = '' + (strString.substring(0, intPosition) + strReplace + strString.substring((intPosition + strFind.length), strString.length)); } return strString; }
ลองของจริงโดยการ ดาวน์โหลดไฟล์ที่นี่
1 Comment »
RSS feed for comments on this post. TrackBack URL
แจ๋วไปเลยครับ ตอนแรกนึกว่าจะมีการ Reload หน้าจอหลัก แต่ว่าไม่มีเลยแฮ๊ะ