ប្រការដ៏ល្អ យើងគួរតែបង្កើតដំណាងមួយនៅក្នុងក្បួនឬវិធីឆ្លើយតបហេតុការណ៍ ក្នុងគោលបំណងចាំទទួលយកវត្ថុនៃថ្នាក់ Event Object ។ ជាទូទៅ គេនិយមប្រើប្រាស់ដំណាងឈ្មោះ «e» ឬ «event» សំរាប់ចាំទទួលយកវត្ថុនោះ។ ពិនិត្យកម្មវិធីខាងក្រោមនេះ៖
<!DOCTYPE html> <html> <head> <link href='https://fonts.googleapis.com/css?family=Odor+Mean+Chey' rel='stylesheet'> </head> <body style="font:14px/1.5 'Odor Mean Chey'"> <input id="ch-color" type="button" value="ប៊ូតុងចុច" /> <input type="color" id="favcolor" value="#ff0000"> <script> function myFunction(event){ var color = document.getElementById("favcolor").value; var element = document.getElementsByTagName("body")[0]; element.style.backgroundColor = color; var info = "ហេតុការណ៍ "+ event.type + " បានកើតឡើងចេញ"; info += "ពីធាតុ HTML មានឈ្មោះជា «"+ event.target.value + "»"; alert(info); } var btn = document.getElementById("ch-color"); btn.addEventListener("click", myFunction); </script> </body> </html>
នៅលើបន្ទាត់លេខ 10 គឺជាការបង្កើតដំណាងមួយមានឈ្មោះថា event នៅក្នុងក្បួនឆ្លើយតបហេតុការណ៍ឈ្មោះ myFunction ដើម្បីចាំទទួលយកដំណឹងដែលជាវត្ថុមួយប្រភេទ ដែលនឹងត្រូវបង្កើតឡើងចេញពីថ្នាក់ Event Object នៅពេលមានហេតុការណ៍ណាមួយកើតមានឡើង។
នៅលើបន្ទាត់លេខ 15 ការសរសេរថា event.type គឺជាការយកសម្បត្តិឈ្មោះ type របស់វត្ថុកើតចេញពីហេតុការណ៍មកប្រើការ។ សម្បត្តិ type ជាប្រភេទរបស់ហេតុការណ៍ដែលបានកើតមានឡើង។ នៅក្នុងកម្មវិធីខាងលើ type គឺជាហេតុការណ៍មានឈ្មោះថា click ។
នៅលើបន្ទា់ត់លេខ 16 ការសរសេរថា event.target.value គឺជាការយកសម្បត្តិ target មកប្រើការ។ សម្បត្តិនេះគឺជាធាតុ HTML ដែលបានធ្វើអោយហេតុការណ៍កើតមានឡើង។
ក្រៅពីសម្បត្តិ type និង target នៅមានសម្បត្តិជាច្រើនទៀត ដែលអាចត្រូវយកមកប្រើប្រាស់នៅក្នុងកាលទេសខុសៗគ្នា៕
Property/Method | Description |
---|---|
bubbles | Returns whether or not a specific event is a bubbling event |
cancelBubble | Sets or returns whether the event should propagate up the hierarchy or not |
cancelable | Returns whether or not an event can have its default action prevented |
composed | Returns whether the event is composed or not |
createEvent() | នCreates a new event |
composedPath() | Returns the event's path |
currentTarget | Returns the element whose event listeners triggered the event |
defaultPrevented | Returns whether or not the preventDefault() method was called for the event |
eventPhase | Returns which phase of the event flow is currently being evaluated |
isTrusted | Returns whether or not an event is trusted |
preventDefault() | Cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur |
stopImmediatePropagation() | Prevents other listeners of the same event from being called |
stopPropagation() | Prevents further propagation of an event during event flow |
target | Returns the element that triggered the event |
timeStamp | Returns the time (in milliseconds relative to the epoch) at which the event was created |
type | Returns the name of the event |