我对这段代码有疑问,当我单击按钮时,它应该执行“hello”功能并打开警报,但它不起作用。
function hello(){
alert("hi");
}
document.getElementById("one").onclick = hello();
<button id="one">Click me </button>
我知道我可以这样做
button onclick="hello()";
but I need it to work with the javascript version. Basically my question is: Is there a way to open the function "hello" when I click the button without putting the onclick in the button tag??
这是一个常见问题,但我找不到规范的答案来链接到您。
您的问题这一行:
document.getElementById("one").onclick = hello()
which executes功能hello
然后将该函数的返回值分配给onclick
.
你真的想要这个:
document.getElementById("one").onclick = hello;
它将函数引用分配给 onclick 属性。
也就是说,使用onclick
相当过时并且使用addEventListener https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener出于多种原因被推荐。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)