HTML DOM Document addEventListener ()
Các ví dụ
Thêm sự kiện nhấp chuột vào tài liệu:
document.addEventListener("click", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
Cú pháp đơn giản hơn:
document.addEventListener("click", function(){
document.getElementById("demo").innerHTML = "Hello World";
});
Thêm ví dụ bên dưới.
Định nghĩa và Cách sử dụng
Phương addEventListener()
thức đính kèm một trình xử lý sự kiện vào tài liệu.
Xem thêm:
Hướng dẫn sử dụng HTML DOM EventListener
Phương thức Document removeEventListener ()
Cú pháp
document.addEventListener(event, function, useCapture)
Thông số
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.
|
Giá trị trả lại
NONE |
Các ví dụ khác
Bạn có thể thêm nhiều trình nghe sự kiện vào tài liệu:
document.addEventListener("click", myFunction1);
document.addEventListener("click", myFunction2);
Bạn có thể thêm các loại sự kiện khác nhau:
document.addEventListener("mouseover", myFunction);
document.addEventListener("click", someOtherFunction);
document.addEventListener("mouseout", someOtherFunction);
Khi chuyển các tham số, hãy sử dụng một "hàm ẩn danh" để gọi một hàm có các tham số:
document.addEventListener("click", function() {
myFunction(p1, p2);
});
Thay đổi màu nền của tài liệu:
document.addEventListener("click", function(){
document.body.style.backgroundColor = "red";
});
Sử dụng phương thức removeEventListener ():
// Add an event listener
document.addEventListener("mousemove", myFunction);
// Remove event listener
document.removeEventListener("mousemove", myFunction);
Hỗ trợ trình duyệt
document.addEventListener
là một tính năng DOM Mức 2 (2001).
Nó được hỗ trợ đầy đủ trong tất cả các trình duyệt:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |