下面这段代码在我写完之后怎么看都是没啥问题的,但是一运行就是报错。然后就去搜,找了一下无非就是
1. 包在window.onload里面
2. 把script标签移动到下边。
但是都没有作用。
最后,我把window.onload去掉,问题终于暴露出来了。btn is not defined!!!
我没把ID给加上引号。。。。没谁了。
错误代码:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
window.onload = function () {
let elementById = document.getElementById(btn);
elementById.onclick = function () {
alert("hello");
}
}
</script>
</head>
<body>
<button id="btn">SayHello</button>
</body>
</html>
正确代码:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
window.onload = function () {
let elementById = document.getElementById("btn");
elementById.onclick = function () {
alert("hello");
}
}
</script>
</head>
<body>
<button id="btn">SayHello</button>
</body>
</html>