jQuery on()วิธี การ
ตัวอย่าง
แนบเหตุการณ์คลิกกับ <p> องค์ประกอบ:
$("p").on("click", function(){
alert("The paragraph was clicked.");
});
ความหมายและการใช้งาน
on() วิธีการแนบตัวจัดการเหตุการณ์อย่างน้อยหนึ่งรายการสำหรับองค์ประกอบที่เลือกและองค์ประกอบย่อย
ตั้งแต่ jQuery เวอร์ชัน 1.7 เมธอด on() เป็นการแทนที่เมธอดใหม่สำหรับการผูก (), live() และเมธอด delegate() วิธีนี้ทำให้ API มีความสอดคล้องกันอย่างมาก และเราแนะนำให้คุณใช้วิธีนี้ เนื่องจากจะทำให้ฐานโค้ด jQuery ง่ายขึ้น
หมายเหตุ:ตัวจัดการเหตุการณ์ที่แนบมาโดยใช้เมธอด on() จะทำงานทั้งองค์ประกอบปัจจุบันและองค์ประกอบในอนาคต (เช่น องค์ประกอบใหม่ที่สร้างโดยสคริปต์)
เคล็ดลับ:หากต้องการลบตัวจัดการเหตุการณ์ ให้ใช้เมธอดoff()
เคล็ดลับ:หากต้องการแนบเหตุการณ์ที่ทำงานเพียงครั้งเดียวแล้วลบตัวเองออก ให้ใช้เมธอดone()
ไวยากรณ์
$(selector).on(event,childSelector,data,function,map)
Parameter | Description |
---|---|
event | Required. Specifies one or more event(s) or namespaces to attach to the selected elements. Multiple event values are separated by space. Must be a valid event |
childSelector | Optional. Specifies that the event handler should only be attached to the specified child elements (and not the selector itself, like the deprecated delegate() method). |
data | Optional. Specifies additional data to pass along to the function |
function | Required. 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 selected elements, and functions to run when the events occur |
ลองด้วยตัวคุณเอง - ตัวอย่าง
วิธีแนบหลายเหตุการณ์กับองค์ประกอบ
วิธีแนบตัวจัดการเหตุการณ์หลายตัวกับองค์ประกอบที่เลือกโดยใช้พารามิเตอร์แผนที่
วิธีแนบเหตุการณ์เนมสเปซที่กำหนดเองบนองค์ประกอบ
วิธีการส่งต่อข้อมูลไปยังฟังก์ชัน
แสดงว่าวิธีการ on() ยังใช้ได้กับองค์ประกอบที่ยังไม่ได้สร้าง
วิธีลบตัวจัดการเหตุการณ์โดยใช้ off() วิธีการ