เอกสาร HTML DOM removeEventListener()
ตัวอย่าง
ลบเหตุการณ์ "mousemove" ที่แนบกับเมธอด addEventListener() ออก:
// Attach an event handler to the document
document.addEventListener("mousemove", myFunction);
// Remove the event handler from the document
document.removeEventListener("mousemove", myFunction);
ตัวอย่าง "ลองใช้เอง" เพิ่มเติมด้านล่าง
ความหมายและการใช้งาน
document.removeEventListener() วิธีการเอาตัวจัดการเหตุการณ์ที่แนบมากับdocument.addEventListener() วิธีการ
หมายเหตุ:ในการลบตัวจัดการเหตุการณ์ ฟังก์ชันที่ระบุด้วยเมธอด addEventListener() ต้องเป็นฟังก์ชัน "named" ภายนอก เช่นในตัวอย่างด้านบน (myFunction)
ฟังก์ชันที่ไม่ระบุชื่อ เช่น "document.removeEventListener(" event ", function(){ myScript });" จะไม่ทำงาน.
เคล็ดลับ:ใช้ องค์ประกอบ .addEventListener()และ องค์ประกอบ .removeEventListener() วิธีการเพิ่ม/ลบตัวจัดการเหตุการณ์ไปยัง/จากองค์ประกอบที่ระบุ
ไวยากรณ์
document.removeEventListener(event, function, useCapture)
ค่าพารามิเตอร์
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:
|
รายละเอียดทางเทคนิค
รุ่น DOM: | เหตุการณ์ DOM ระดับ 2 |
---|---|
คืนมูลค่า: | ไม่มีค่าส่งคืน |
บันทึกการเปลี่ยนแปลง: | พารามิเตอร์ useCapture กลายเป็นตัวเลือกเสริมใน Firefox 6 และ Opera 12.0 (เป็นตัวเลือกสำหรับ Chrome, IE และ Safari เสมอ) |
ตัวอย่างเพิ่มเติม
ตัวอย่าง
สำหรับเบราว์เซอร์ที่ไม่สนับสนุนเมธอด removeEventListener() คุณสามารถใช้เมธอด detachEvent() ได้
ตัวอย่างนี้แสดงให้เห็นถึงโซลูชันข้ามเบราว์เซอร์:
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);
}
หน้าที่เกี่ยวข้อง
บทช่วยสอน JavaScript: HTML DOM EventListener
การอ้างอิง JavaScript: องค์ประกอบ .removeEventListener()
รองรับเบราว์เซอร์
document.removeEventListener()
เป็นคุณลักษณะ DOM ระดับ 2 (2001)
ได้รับการสนับสนุนอย่างเต็มที่ในเบราว์เซอร์ทั้งหมด:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |