Uncaught TypeError: Cannot read property 'style' of undefined求解

wu505785951 2017-02-25 09:31:28

window.onload = function(){
var str = document.getElementsByTagName("tr");
for(var i = 0; i < str.length; i++)
{
str[i].onmouseover=function() {
this.style.backgroundColor="#f2f2f2";
}

str[i].onmouseout = function()
{
str[i].style.backgroundColor = "#fff";
}
}


}

第一个onmouseover因为用的是this所以可以改变背景颜色,但当鼠标移开时就显示Uncaught TypeError: Cannot read property 'style' of undefined报错,实在不明白为什么不可以直接用
str[i].style.backgroundColor, 而用this指代后就能成功运行。
...全文
886 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
天际的海浪 2017-02-25
  • 打赏
  • 举报
回复
事件执行时,for循环早就结束了,这个时候i已经是最大值加1了。 解决方法是能用this情况就要用this,或者用闭包把每次循环i的值保存起来。
cn00439805 2017-02-25
  • 打赏
  • 举报
回复
楼上正解 闭包你可以: for(var i = 0; i < str.length; i++){ (function(i){ //代码 })(i) }

87,990

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧