简体   繁体   English

html onclick 事件未触发

[英]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.我想我缺少一些关于 html、javascript、DOM 和传播或类似内容的基础知识,但我找不到任何相关的问题/答案。

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. MyButton1工作正常。 MyButton2 isn't firing the onclick event. MyButton2没有触发 onclick 事件。

The question is simple: why MyButton2 isn't firing the event?问题很简单:为什么MyButton2没有触发事件?

As there's a click method on the DOM element corresponding to the button element, name your function anything other than click :由于在与button元素对应的 DOM 元素上有一个click方法,因此将您的 function 命名为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() :请注意:您应该避免使用内联事件处理程序,而是可以使用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!让您 function 名称相同!

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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