简体   繁体   中英

Button doesn't do anything when clicked

在此处输入图像描述 So I have a HTML file with a button, and an external js file that should have some functionality. But it doesn't work. Here's the code:

HTML full code:

 const btn = document.getElementById("play"); btn.addEventListener("click", alertMessage); function alertMessage() { alert("Pls tell me youre working..."); }
 <html> <body> <div class="text-box"> <h1>BLOG</h1> </div> <div class="buttons"> <button id="play"> OK </button> </div> <script src="music-player/scripts/app.js"></script> </body> </html>

Because that make Maximum call stack size because the alert inside the function will not refer to the default global alert but to the function itself which makes an infinity recursion, you need to change the function name.

 const btn = document.getElementById("play"); btn.addEventListener("click", alertMessage); function alertMessage() { alert("Pls tell me youre working..."); }
 <div class= "buttons"> <button id="play"> OK </button> </div> <script src="music-player/scripts/app.js"></script>

If you used window.alert() and used function expression instead of a function declaration ( which overite the global alert ) it will work fine, but for sure it would better to change the function name to prevent conflicts.

 const alert = () => { window.alert("Pls tell me youre working..."); } const btn = document.getElementById("play"); btn.addEventListener("click", alert);
 <div class= "buttons"> <button id="play"> OK </button> </div> <script src="music-player/scripts/app.js"></script>

Update function name:

 const btn = document.getElementById("play"); btn.addEventListener("click", alertMessage); function alertMessage() { alert("Pls tell me youre working..."); }
 <html> <body> <div class="text-box"> <h1>BLOG</h1> </div> <div class="buttons"> <button id="play"> OK </button> </div> <script src="music-player/scripts/app.js"></script> </body> </html>

change the name of the function from alert to something else or you can add directly add onClick="function()" in button tag it self

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM