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("div");
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代码:
<body>
<div id="side_box">
<div id="side_tool">
<ul>
<li class="side_list" index="1"></li>
<li class="side_list" index="2"></li>
<li class="side_list" index="3"></li>
<li class="side_list" index="4"></li>
<li class="side_list" index="5"></li>
<li class="side_list" index="6"></li>
</ul>
</div>
<div id="side_content">
<div class="main_content" index="1" style="background-color: red; display: none;"></div>
<div class="main_content" index="2" style="background-color: yellow; display: none;"></div>
<div class="main_content" index="3" style="background-color: black; display: none;"></div>
<div class="main_content" index="4" style="background-color: #888; display: none;"></div>
<div class="main_content" index="5" style="background-color: #850; display: none;"></div>
<div class="main_content" index="6" style="background-color: #058; display: none;"></div>
</div>
</div>
<script src="js/main.js"></script>
</body>
又遇到这个 for 循环和异步调用的问题了,请参考我在这个问题下的回答:https://segmentfault.com/q/1010000005797985/a-1020000005798132