ทบทวน ลำดับ การทำงาน keyboard events ของ input text ใน jQuery
เขียนเมื่อ 12 ปีก่อน โดย Ninenik Narkdeekeyboard event input text mouse event event jquery
คำสั่ง การ กำหนด รูปแบบ ตัวอย่าง เทคนิค ลูกเล่น การประยุกต์ การใช้งาน เกี่ยวกับ keyboard event input text mouse event event jquery
เนื้อหาส่วนนี้เป็นการ ทบทวน ลำดับ events ของ keyboard และ mouse บางส่วน
ในการใช้งาน กับ input text element จะแบ่งออกเป็น 2 กรณี ในการแนะนำ
กรณีที่ 1 เริ่มตั้งแต่ การใช้ปุ่ม Tab ใน keyboard เลื่อนไปยัง input text element
ลำดับ events จะเป็นดังนี้
// เริ่มกดแท็บ เข้ามาใน input text
1.focusin
2.focus
3.keyup
// 4 - 6 เป็นกรณีการพิมพ์ข้อมูลเข้าไปใน input text
4.keydown
5.keypress
6.keyup
// กดแท็บออกจาก input text
7.keydown
8.change
9.focusout
กรณีที่ 2 เริ่มจากการใช้ mouse คลิกที่ input text element
ลำดับ events จะเป็นดังนี้
// เริ่มคลิกที่ input text
1.focusin
2.focus
3.click
// 4 - 6 เป็นกรณีการพิมพ์ข้อมูลเข้าไปใน input text
4.keydown
5.keypress
6.keyup
// คลิกเมาส์ด้านนอก input text
7.change
8.focusout
หมายเหตุ::
--- ถ้าไม่มีการพิมพ์ หรือแก้ไขข้อมูล ใน input text แล้ว
event ที่ 4 ถึง 6 และ 8 ในกรณีที่ 1 จะไม่เกิดขึ้น
event ที่ 4 ถึง 7 ในกรณีที่ 2 จะไม่เกิดขึ้น
ถ้า cursor สำหรับพิมพ์อยู่ที่ input text แล้ว หากทำการคลิกซ้ำ
event ที่ 1 และ 2 ในกรณีที่ 2 จะไม่เกิดขึ้น
ตัวอย่างโค้ดทั้งหมดสำหรับทดสอบ (console.log ใช้ firebug หรือ developer tools)
<!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>keyboard event</title> </head> <body> <input type="text" name="text1" id="text1" on /> <br /> <br /> <input type="password" name="text2" id="text2" /> <br /> <br /> <input type="text" name="text3" id="text3" /> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript"> $(function(){ $("#text2").focus(function(){ console.log("focus"); }); $("#text2").focusin(function(){ console.log("focusin"); }); $("#text2").focusout(function(){ console.log("focusout"); }); $("#text2").keyup(function(){ console.log("keyup"); }); $("#text2").keydown(function(){ console.log("keydown"); }); $("#text2").click(function(){ console.log("click"); }); $("#text2").change(function(){ console.log("change"); }); $("#text2").keypress(function(){ console.log("keypress"); }); }); </script> </body> </html>
