Acabo de empezar a aprender javascript y he creado un pequeño programa para crear una alerta cuando se hace clic en un botón, pero no funciona y no estoy seguro de por qué.
Aquí está mi código:
<html> <head> <style> body { background-color: grey; color: white; } </style> <script> const some_action = () => { window.alert("hi") } document.getElementById("btn").addEventListener("click", some_action) </script> </head> <body> <p> <button id="btn">click me</button> </p> </body> </html>O, alternativamente, podría hacer un archivo adjunto de evento delegado:
<html> <head> <style> body { background-color: grey; color: white; } </style> <script> const some_action = ev => { if (ev.target.id === "btn") window.alert("hi") } document.addEventListener("click", some_action) </script> </head> <body> <p> <button id="btn">click me</button> </p> </body> </html>