หนึ่งตัวจัดการสำหรับหลายองค์ประกอบใน JavaScript

สามารถผูกฟังก์ชันเดียวกับหลายองค์ประกอบได้ทันที ตัวอย่างเช่น ลองพิจารณาฟังก์ชันต่อไปนี้:

javascriptfunction func() {
  console.log('!!!');
}

นอกจากนี้ยังมีปุ่มสองปุ่ม:

html<input id="button1" type="submit" value="button1">
<input id="button2" type="submit" value="button2">

รับการอ้างอิงไปยังปุ่มเหล่านี้ลงในตัวแปร:

javascriptlet button1 = document.querySelector('#button1');
let button2 = document.querySelector('#button2');

ทีนี้ลองผูกฟังก์ชัน func ของเรา กับทั้งปุ่มแรกและปุ่มที่สอง:

javascriptbutton1.addEventListener('click', func);
button2.addEventListener('click', func);
Задание 1

มี 5 ย่อหน้า:

html<p id="elem1">text</p>
<p id="elem2">text</p>
<p id="elem3">text</p>
<p id="elem4">text</p>
<p id="elem5">text</p>

ให้ฟังก์ชันต่อไปนี้:

javascriptfunction func() {
  console.log('message');
}

ผูกฟังก์ชันนี้กับย่อหน้าทั้ง 5 ย่อหน้า