HTML DOM Document removeEventListener ()
Thí dụ
Xóa sự kiện "mousemove" đã được đính kèm với phương thức addEventListener ():
// Attach an event handler to the document
document.addEventListener("mousemove", myFunction);
// Remove the event handler from the document
document.removeEventListener("mousemove", myFunction);
Thêm các ví dụ "Hãy tự mình thử" bên dưới.
Định nghĩa và Cách sử dụng
Phương thức document.removeEventListener () loại bỏ trình xử lý sự kiện đã được đính kèm với phương thức document.addEventListener () .
Lưu ý: Để loại bỏ trình xử lý sự kiện, hàm được chỉ định với phương thức addEventListener () phải là một hàm bên ngoài, "được đặt tên", giống như trong ví dụ trên (myFunction).
Các hàm ẩn danh, như "document.removeEventListener (" event ", function () { myScript });" sẽ không làm việc.
Mẹo: Sử dụng phương thức phần tử .addEventListener () và phần tử .removeEventListener () để thêm / xóa trình xử lý sự kiện vào / khỏi một phần tử được chỉ định.
Cú pháp
document.removeEventListener(event, function, useCapture)
Giá trị tham số
Parameter | Description |
---|---|
event | Required. A String that specifies the name of the event to remove. Note: Do not use the "on" prefix. For example, use "click" instead of "onclick". Tip: For a list of all HTML DOM events, look at our complete HTML DOM Event Object Reference. |
function | Required. Specifies the function to remove. |
useCapture |
Optional. A Boolean value that specifies the event phase
to remove the event handler from. Possible values:
|
Chi tiết kỹ thuật
Phiên bản DOM: | Sự kiện DOM cấp 2 |
---|---|
Giá trị trả lại: | Không có giá trị trả lại |
Changelog: | Tham số useCapture trở thành tùy chọn trong Firefox 6 và Opera 12.0 (luôn là tùy chọn cho Chrome, IE và Safari) |
Các ví dụ khác
Thí dụ
Đối với các trình duyệt không hỗ trợ phương thức removeEventListener (), bạn có thể sử dụng phương thức detachEvent ().
Ví dụ này minh họa một giải pháp trình duyệt chéo:
if (document.removeEventListener) { // For all major browsers, except IE 8 and earlier
document.removeEventListener("mousemove", myFunction);
} else if (document.detachEvent) { // For IE 8 and earlier versions
document.detachEvent("onmousemove", myFunction);
}
Các trang liên quan
Hướng dẫn JavaScript: HTML DOM EventListener
Tham chiếu JavaScript: element .removeEventListener ()
Hỗ trợ trình duyệt
document.removeEventListener()
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 |