JavaScript getElementByID() 不起作用
为什么下面的 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>
Why does refButton
get null
in the following JavaScript code?
<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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您调用函数时,页面的其余部分尚未呈现,因此该元素此时不存在。尝试在
window.onload
上调用您的函数。像这样的东西:At the point you are calling your function, the rest of the page has not rendered and so the element is not in existence at that point. Try calling your function on
window.onload
maybe. Something like this:您需要将 JavaScript 放在 body 标记的末尾。
它找不到它,因为它还不在 DOM 中!
您还可以将其包装在 onload 事件处理程序中,如下所示:
You need to put the JavaScript at the end of the body tag.
It doesn't find it because it's not in the DOM yet!
You can also wrap it in the onload event handler like this:
因为当脚本执行时浏览器还没有解析
,所以它不知道有指定id的元素。
请尝试这样做:
请注意,您也可以使用
addEventListener
而不是window.onload = ...
来使该函数仅在解析整个文档后执行。Because when the script executes the browser has not yet parsed the
<body>
, so it does not know that there is an element with the specified id.Try this instead:
Note that you may as well use
addEventListener
instead ofwindow.onload = ...
to make that function only execute after the whole document has been parsed.