jQuery off()เมธอด

❮ วิธีการจัดกิจกรรม jQuery

ตัวอย่าง

ลบเหตุการณ์คลิกสำหรับองค์ประกอบ <p> ทั้งหมด:

$("button").click(function(){
  $("p").off("click");
});

ความหมายและการใช้งาน

วิธี off() มักใช้เพื่อลบตัวจัดการเหตุการณ์ที่แนบมากับวิธี on ()

สำหรับ jQuery เวอร์ชัน 1.7 วิธี off() เป็นการแทนที่ใหม่สำหรับวิธี unbind(), die() และ undelegate() วิธีนี้ทำให้ API มีความสอดคล้องกันอย่างมาก และเราแนะนำให้คุณใช้วิธีนี้ เนื่องจากจะทำให้ฐานโค้ด jQuery ง่ายขึ้น 

หมายเหตุ:หากต้องการลบตัวจัดการเหตุการณ์เฉพาะ สตริงตัวเลือกต้องตรงกับสตริงที่ส่งผ่านไปยังเมธอด on() เมื่อแนบตัวจัดการเหตุการณ์ 

เคล็ดลับ:หากต้องการแนบเหตุการณ์ที่ทำงานเพียงครั้งเดียวแล้วลบตัวเองออก ให้ใช้เมธอดone()


ไวยากรณ์

$(selector).off(event,selector,function(eventObj),map)

Parameter Description
event Required. Specifies one or more events or namespaces to remove from the selected element(s).

Multiple event values are separated by a space. Must be a valid event
selector Optional. A selector which should match the one originally passed to the on() method when attaching event handlers
function(eventObj) Optional. Specifies the function to run when the event occurs
map Specifies an event map ({event:function, event:function, ...}) containing one or more event to attach to the elements, and functions to run when the events occur

ลองด้วยตัวคุณเอง - ตัวอย่าง


วิธีลบตัวจัดการเหตุการณ์การคลิกทั้งหมดสำหรับองค์ประกอบ <p> ทั้งหมดที่เพิ่มด้วยเมธอด on()


วิธีลบฟังก์ชันเฉพาะที่เพิ่มด้วย on() วิธีการ


วิธีลบตัวจัดการเหตุการณ์หลังจากที่เหตุการณ์ถูกทริกเกอร์ตามจำนวนครั้งที่กำหนด


❮ วิธีการจัดกิจกรรม jQuery