مستند HTML DOM ، addEventListener ()
أمثلة
أضف حدث النقر إلى المستند:
document.addEventListener("click", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
بناء جملة أبسط:
document.addEventListener("click", function(){
document.getElementById("demo").innerHTML = "Hello World";
});
المزيد من الأمثلة أدناه.
التعريف والاستخدام
تقوم addEventListener()
الطريقة بإرفاق معالج حدث بالمستند.
أنظر أيضا:
برنامج HTML DOM EventListener التعليمي
المستند طريقة removeEventListener ()
بناء الجملة
document.addEventListener(event, function, useCapture)
المعلمات
Parameter | Description |
event | Required. The event name. Do not use the "on" prefix. For example, use "click" instead of "onclick". HTML DOM events are listed in Complete HTML DOM Event Object Reference. |
function | Required. The function to run when the event occurs. When the event occurs, an event object is passed to the function as the first parameter. The type of the event object depends on the specified event. For example, the "click" event belongs to the MouseEvent object. |
useCapture |
Optional. A boolean. Specifies if the event should be executed in the capturing or in the bubbling phase (default). true - The event handler is executed in the capturing phase.false - The event handler is executed in the bubbling phase.
|
قيمة الإرجاع
NONE |
مزيد من الأمثلة
يمكنك إضافة العديد من مستمعي الأحداث إلى المستند:
document.addEventListener("click", myFunction1);
document.addEventListener("click", myFunction2);
يمكنك إضافة أنواع مختلفة من الأحداث:
document.addEventListener("mouseover", myFunction);
document.addEventListener("click", someOtherFunction);
document.addEventListener("mouseout", someOtherFunction);
عند تمرير المعلمات ، استخدم "anonymous function" لاستدعاء دالة مع المعلمات:
document.addEventListener("click", function() {
myFunction(p1, p2);
});
قم بتغيير لون خلفية المستند:
document.addEventListener("click", function(){
document.body.style.backgroundColor = "red";
});
باستخدام طريقة () removeEventListener:
// Add an event listener
document.addEventListener("mousemove", myFunction);
// Remove event listener
document.removeEventListener("mousemove", myFunction);
دعم المتصفح
document.addEventListener
هي ميزة DOM من المستوى 2 (2001).
إنه مدعوم بالكامل في جميع المتصفحات:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |