Uncaught TypeError: Cannot read properties of null (reading ‘getElementsByTagName‘)
想要鼠标悬停,li标签变色var ps= document.getElementById("navigation").getElementsByTagName("li");for (var i in ps) {ps[i].onmouseover = function () {this.setAttribute("class","active");}ps[i].onmouseou
·
想要鼠标悬停,li标签变色
var ps= document.getElementById("navigation").getElementsByTagName("li");
for (var i in ps) {
ps[i].onmouseover = function () {
this.setAttribute("class","active");
}
ps[i].onmouseout = function () {
this.removeAttribute("class");
}
}
结果浏览器报错
后来发现是script标签放在了head中,如果没有设置window.onload,那么JS在html加载之前就会被解析,相应的就取不到html中的元素了。
<script>
window.onload = function () {
var ps= document.getElementById("navigation").getElementsByTagName("li");
for (var i in ps) {
ps[i].onmouseover = function () {
this.setAttribute("class","active");
}
ps[i].onmouseout = function () {
this.removeAttribute("class");
}
}
}
</script>
更多推荐
已为社区贡献1条内容
所有评论(0)