Tài liệu DOM HTML addEventListener()
Ví dụ
Thêm một 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";
}
Hãy tự mình thử »Cú pháp đơn giản hơn:
document.addEventListener("click", function(){
document.getElementById("demo").innerHTML = "Hello World";
});
Hãy tự mình thử »Thêm ví dụ dưới đây.
Sự miêu tả
Phương thức addEventListener()
gắn một trình xử lý sự kiện vào một tài liệu.
Phương thức phần tử
Phương thức addEventListener()
Phương thức RemoveEventListener()
Phương pháp tài liệu
Phương thức addEventListener()
Phương thức RemoveEventListener()
Hướng dẫn
Cú pháp
document.addEventListener( event , function , Capture )
Thông số
Parameter | Description |
event | Required. The event name. Do not use the "on" prefix. Use "click" instead of "onclick". All HTML DOM events are listed in the: 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. |
capture |
Optional (default = false).true - The handler is executed in the capturing phase.false - The handler is executed in the bubbling phase.
|
Giá trị trả về
NONE |
Thêm ví dụ
Bạn có thể thêm nhiều trình xử lý sự kiện vào tài liệu:
document.addEventListener("click", myFunction1);
document.addEventListener("click", myFunction2);
Hãy tự mình thử »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);
Hãy tự mình thử »Khi truyền tham số, hãy sử dụng "hàm ẩn danh" để gọi hàm có tham số:
document.addEventListener("click", function() {
myFunction(p1, p2);
});
Hãy tự mình thử »Thay đổi màu nền của tài liệu:
document.addEventListener("click", function(){
document.body.style.backgroundColor = "red";
});
Hãy tự mình thử »Sử dụng phương thức RemoveEventListener():
// Add an event listener
document.addEventListener("mousemove", myFunction);
// Remove event listener
document.removeEventListener("mousemove", myFunction);
Hãy tự mình thử »Hỗ trợ trình duyệt
document.addEventListener
là tính năng DOM Cấp 2 (2001).
Nó được hỗ trợ đầy đủ trong tất cả các trình duyệt:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |