为什么会refButton获得null以下JavaScript代码?
refButton
null
<html> <head> <title></title> <script type="text/javascript"> var refButton = document.getElementById("btnButton"); refButton.onclick = function() { alert('I am clicked!'); }; </script> </head> <body> <form id="form1"> <div> <input id="btnButton" type="button" value="Click me"/> </div> </form> </body> </html>
此时,您正在调用函数,页面的其余部分尚未呈现,因此该元素当时不存在。尝试调用您的函数window.onload。像这样:
window.onload
<html> <head> <title></title> <script type="text/javascript"> window.onload = function(){ var refButton = document.getElementById("btnButton"); refButton.onclick = function() { alert('I am clicked!'); } }; </script> </head> <body> <form id="form1"> <div> <input id="btnButton" type="button" value="Click me"/> </div> </form> </body> </html>