ЗадачаHTML has <button id='b'>click me</button>. Add a click listener that logs 'clicked!' to console every time the button is clicked.
addEventListener: щракнете и обекта на събитието
75 XP7 min
Теория
The event-listener pattern
button.addEventListener("click", (event) => {
console.log("clicked", event.target);
});Three parts:
- The event name —
"click","input","submit","keydown", etc. - The handler — your callback. Gets an
eventargument. event.target— the element that triggered the event. Useful in delegation (C2-08).
Why addEventListener beats onclick
button.onclick = first;
button.onclick = second; // first is OVERWRITTEN
button.addEventListener("click", first);
button.addEventListener("click", second); // BOTH runonclick = clobbers any previous handler. addEventListener stacks. The latter is the only sane choice in any non-trivial codebase.
removeEventListener — pass the same function
const handler = () => { /* ... */ };
button.addEventListener("click", handler);
button.removeEventListener("click", handler); // worksIf you wrote addEventListener("click", () => { ... }) with an inline arrow, you CAN'T remove it later — there's no reference. Name your handler if you'll need to remove it.
🔒
Регистрирай се за да започнеш да кодираш
Теорията е отворена за всички. Редакторът, живият преглед и проверката се отключват с 7-дневен безплатен пробен период — нужна е карта.
Регистрация — безплатен пробен период →Първите 10 урока във всеки път са безплатни. Без карта.