ก่อนที่จะมี javascript libraries ต่างๆ เช่น jQuery ,Prototype เป็นต้น หากต้องการที่จะใช้ event เช่น การคลิก click events สำหรับ element ใดๆ ที่ต้องการแล้ว สามารถทำได้โดยใช้ โค้ต javascript ข้างล่างต่อไปนี้
ใช้งาน Events เรียกใช้ฟังก์ชันโดยตรง
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <script type= "text/javascript" > var DOMobj = document.getElementById( "myButton" ); // เรียกใช้ฟังก์ชันโดยตรง if (DOMobj.addEventListener){ DOMobj.addEventListener( "click" , function () { alert( 'button clicked' ); }, false ); } else if (DOMobj.attachEvent){ DOMobj.attachEvent( "onclick" , function () { alert( 'button clicked' ); }); } else { DOMobj.onclick = function () { alert( 'button clicked' ); } } </script> |
ใช้งาน Events เรียกฟังก์ชันผ่านตัวแปร
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <script type= "text/javascript" > // สร้างตัวแปรเก็บฟังก์ชันที่ต้องการ var myFunction= function (){ alert( 'button clicked' ); } var DOMobj = document.getElementById( "myButton" ); // เรียกใช้ฟังก์ชันผ่านตัวแปรชื่อ myFunction if (DOMobj.addEventListener){ DOMobj.addEventListener( "click" ,myFunction, false ); } else if (DOMobj.attachEvent){ DOMobj.attachEvent( "onclick" , myFunction); } else { DOMobj.onclick =myFunction; } </script> |