Tengo un botón en un archivo html que, cuando se hace clic, debe ejecutar una función en un archivo de script Java que envía una alerta que dice hey. Esto no sucede y no sé por qué. Se siente como el delgado más simple, pero simplemente no puedo hacer que funcione. Java Script está habilitado en mi navegador (google chrome) No creo que importe, pero por si acaso, estoy codificando en código VS.
function myfunction() { alert("hey"); } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="script.js" type="module"></script> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div id="head"> <h1>Park Stats</h1> </div> <table> <tr id="head_row"> <th>Player</th> <th>Points</th> <th>Rebounds</th> <th>Blocks</th> <th>Steals</th> <th>Fouls</th> <th>Scrum Wins</th> <th>Scrum Losses</th> <th>Assists</th> </tr> <tr> <td>Player Name<button class="name_button">✎</button></td> <td> <div class="container"> <button>-</button> <div id="p1s1" class="stat">0</div> **<button onclick="myfunction();">+</button>** </div> </td> </tr> </table> </body> </html>Si está utilizando su código local y no en un servidor web , debe eliminar el atributo type="module" . ver: módulos javascript y CORS
Cambia esto
<script src="script.js" type="module"></script>A
<script src="script.js"></script>Y ahora me funciona.
**<button onclick="myfunction();">+</button>** debería ser **<button id="alert-button">+</button>**
document.addEventListener('DOMContentLoaded', (event) => { document.getElementById("alert-button").addEventListener('click', function(){ myFunction(); }) });