简体   繁体   中英

html onclick event not firing

I guess I am missing some fundamentals about html, javascript, DOM and propagation or anything like this, but I can't find any relevant question/answer.

Here is my code:

 <html> <head> <script type="text/javascript"> function click(e) { alert(e.target.id); } </script> </head> <body> <input type="button" id="btn1" onclick="alert(event.target.id);" value="MyButton1"> <input type="button" id="btn2" onclick="click(event);" value="MyButton2"> </body> </html>

MyButton1 is working fine. MyButton2 isn't firing the onclick event.

The question is simple: why MyButton2 isn't firing the event?

As there's a click method on the DOM element corresponding to the button element, name your function anything other than click :

 <html> <head> <script type="text/javascript"> function clickMe(e) { alert(e.target.id); } </script> </head> <body> <input type="button" id="btn1" onclick="alert(event.target.id);" value="MyButton1"> <input type="button" id="btn2" onclick="clickMe(event);" value="MyButton2"> </body> </html>

Please note: You should avoid using inline event handler, instead you can use addEventListener() :

 <html> <head> <script type="text/javascript"> window.addEventListener('DOMContentLoaded', () => { document.getElementById('btn1').addEventListener('click', alertMessage); document.getElementById('btn2').addEventListener('click', alertMessage); }); function alertMessage(e){ alert(e.target.id); } </script> </head> <body> <input type="button" id="btn1" value="MyButton1"> <input type="button" id="btn2" value="MyButton2"> </body> </html>

Or You could do this! Keeping you function name same!

Actually I would suggest to do this way(setting these attributes from the script)

 <html> <head> </head> <body> <input type="button" id="btn1" onclick="alert(event.target.id);" value="MyButton1"> <input type="button" id="btn2" value="MyButton2"> <script type="text/javascript"> function click(e) { alert(e.target.id); } document.getElementById("btn2").onclick = click; </script> </body> </html>

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