HYDMonster
2018-11-21 11:03
window.onload = function(){
var tableRows=document.getElementsByTagName("tr");
for(var i=0;i<tableRows.length;i++){
tableRows[i].onmouseover=function(){
tableRows[i].style.backgroundColor="yellow";
}
tableRows[i].onmouseout=function(){
tableRows[i].style.backgroundColor="#CCC";
}
}
}为什么这种设置颜色时,总对初始那两行报Cannot read property 'style' of undefined错误,然后只在新增加一行的上面生效。然后我改成图片那种就没有问题了。我感觉这是差不多的啊。

我的添加代码:

tableRows[i].style.backgroundColor="yellow";
tableRows[i].style.backgroundColor="#CCC";
你把你的这两行代码改成 :this.style.backgroundColor="yellow";this.style.backgroundColor="#CCC";
for循环时用var定义存在变量提升问题,tableRows[i].onmouseover=function(){tableRows[i].style.backgroundColor="yellow";};当执行移入移除的时候i已经循环到tableRows.length;所以只能是最后一个有效果吧。将tableRows[i]改为this时有效果是因为,this指向的是调用这个方法的对象,tableRows[i].onmouseover=function(){this.style.backgroundColor="yellow";};this指向的就是tableRows[i]。
我觉得是这个样子,仅供参考
函数之间存在作用域,具体原理与理论我不太清楚去了.. 大概意思就是tableRows[i]是局部的。。不是全局
JavaScript进阶篇
469060 学习 · 22582 问题
相似问题