Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ผูก Event ให้ Element ที่สร้างแบบไดนามิกด้วย Event Delegation

Event Delegation: จัดการ Event ของ Element ที่ยังไม่มีอยู่

ใช้ document.addEventListener() ร่วมกับ event.target เพื่อจับ event ของ element ที่เพิ่มเข้ามาในภายหลัง

ตัวอย่างโค้ดเต็ม

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Dynamic Event</title>
</head>
<body>
  <input type="button" value="submit" id="buttonSubmit" />
  
  <script>
    document.addEventListener('click', function(event) {
      if (event.target && event.target.id === 'buttonSubmit') {
        console.log("Event generation on the button click");
      }
    });
    
    // ทดสอบ: เพิ่มปุ่มใหม่แบบไดนามิก
    setTimeout(() => {
      const newBtn = document.createElement('button');
      newBtn.id = 'buttonSubmit';
      newBtn.textContent = 'Dynamic Button';
      document.body.appendChild(newBtn);
    }, 2000);
  </script>
</body>
</html>

วิธีรัน

บันทึกเป็น index.html แล้วเปิดด้วย Live Server

คำอธิบาย

  • Event listener ผูกที่ document (หรือ parent element ที่มีอยู่แล้ว)
  • ตรวจสอบ event.target.id ว่าเป็น element ที่ต้องการหรือไม่
  • Element ที่เพิ่มมาใหม่ (dynamic) ก็จะทำงานได้โดยไม่ต้องผูก event ใหม่
  • หลักการนี้เรียกว่า Event Delegation

รูปแบบ jQuery (legacy)

$(document).on('click', '#buttonSubmit', function() {
  console.log("Clicked!");
});