在javascript中,我正在使用EventListener,并且我得到了TypeError xyz = null
in javascript I'm using EventListener and I get the TypeError xyz = null
//这是我正在使用的代码。在控制台中,我收到错误类型错误xyz = null,请帮助我找出我做错了什么。
<script>
var xyz = document.getElementById("myBtn");
xyz.addEventListener("mouseover", hoverExample1);
xyz.addEventListener("mouseout", hoverExample2);
function hoverExample1() {
document.body.style.backgroundColor = "blue";}
function hoverExample2() {
document.body.style.backgroundColor = "red";}
</script>
<body>
<button type="button" id="myBtn">Hover Experiment 1</button>
</body>
将<script>
作为<body>
的last-child
,而不是将其放在<head>
中。当您访问myBtn
时,它不在DOM
var xyz = document.getElementById("myBtn");
xyz.addEventListener("mouseover", hoverExample1);
xyz.addEventListener("mouseout", hoverExample2);
function hoverExample1() {
document.body.style.backgroundColor = "blue";
}
function hoverExample2() {
document.body.style.backgroundColor = "red";
}
<button type="button" id="myBtn">Hover Experiment 1</button>
这个js脚本甚至在DOM准备好之前就被执行了,此时#myBtn
不可用。如前面的回答所述,您可以将脚本放在标签body
末尾,或者您可以制作代码片段以在window.onload
同时仍然将JS放在HTML部分之前
window.onload = _attachEvent; // a function to wrap all js code
and it will be called onload
function _attachEvent(){
var xyz = document.getElementById("myBtn");
xyz.addEventListener("mouseover", hoverExample1);
xyz.addEventListener("mouseout", hoverExample2);
function hoverExample1() {
document.body.style.backgroundColor = "blue";
}
function hoverExample2() {
document.body.style.backgroundColor = "red";
}
}
您还可以探索 DOMContentLoaded,它也可用于解决此类问题。
工作小提琴
相关文章:
- jquery TypeError: Response is null
- 在javascript中,我正在使用EventListener,并且我得到了TypeError xyz = null
- Quicksort.js未捕获的typeError无法读取null的属性
- Uncaught TypeError:对象原型在Symfony 2中只能是Object或ExtJS为null
- 为什么TypeError:document.getElementById()为null
- TypeError (null reference exception) when using dom-construc
- Rails JavaScript 包含 TypeError:“null”不是一个对象(评估 'document.
- getElementById TypeError: “无法将属性'innerHTML'设置为null
- Ember JS : uncatch TypeError: 無法讀取 null 的屬性 'createRecor
- TypeError: this.element is null, Rails with Judge gem
- TypeError:超级表达式必须是 null 或函数,而不是使用 Babeljs 未定义
- TypeError: jasmine.getEnv().currentSpec is null
- gapi.auth.authorize: TypeError: cv(...) is null
- pdfmake.js uncatch TypeError:无法读取 null 的属性“length”
- Javascript TypeError: document.getElementById(...) is null
- JavaScript :TypeError: document.getElementById(...) is null
- ng-repeat TypeError: 無法讀取 null 的屬性 'insertBefore'
- JavaScript TypeError:无法读取 null 的属性“style”
- TypeError: document.getElementById(..) 为 null - 错误消息
- Javascript 错误:TypeError:“null”不是 safari 上的对象(评估“event.target