chrome浏览器报这样的错误:“Uncaught TypeError: Cannot read property 'style' of undefined”
如果在for循环外绑定就不会出错。
js代码:
window.onload = function(){
var sideList = document.getElementById("side_tool").getElementsByTagName("li");
var contentList = document.getElementById("side_content").getElementsByTagName("p");
for (var i = 0; i < sideList.length; i++){
sideList[i].onmouseover = function(){
contentList[i].style.display = "block";
}
sideList[i].onmouseout = function(){
contentList[i].style.display = "none";
}
}
}
html代码:
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
下标变了,找不到所以报错,
sideList[i].index=i;绑定下标
sideList[this.index];
contentList[this.index];对应的下标
这里的绑定事件是异步执行的,因此当真正执行到
的时候,已经超出了
for的作用域,因此i的值根本就不能按照你的设想等同于当前循环的i。正确做法应该是
用 let 替换 var
用自执行函数与闭包进行解决