javascript - 在遍历数组设置mouseover效果时用for语句效果失效,而数组[1]单独设置反而有效果?
ringa_lee
ringa_lee 2017-04-11 13:22:11
0
6
485

这是一道慕课网上的练习题,在遍历数组设置mouseover效果时用for语句效果失效,而数组[1]单独设置反而有效果?

就是说将代码中
for(x=0;x<3;x++){

tr[x].onmouseover=function(){tr[x] .style.backgroundColor='#11b006';
        };
tr[x].onmouseout=function(){tr[x] .style.backgroundColor='#f2f2f2';
        };    

改成:
tr[1].onmouseover=function(){tr[1] .style.backgroundColor='#11b006';

        };
tr[1].onmouseout=function(){tr[1] .style.backgroundColor='#f2f2f2';
那么mouseover的效果也有了,可是如果用一个遍历去循环设置为啥效果就消失了呢?另外实验了下,引入中间变量也是可以的,例如

for(var i=0;i<cl.length;i++){

        changecolor(tr[i]);
    }
  }
        function changecolor(x){
        x.onmouseover=function(){
            x.style.backgroundColor='#ccc';
        };
        x.onmouseout=function(){
            x.style.backgroundColor='#fff';
        };    

这样就可以实现了,不过不是很清楚为啥这样行。望各位大大解答下。



原来的代码区

<!DOCTYPE html>
<html>
<head>
<title> new document </title>
<meta http-equiv="Content-Type" content="text/html; charset=gbk"/>
<script type="text/javascript">

 
  window.onload = function(){

var tr=document.getElementsByTagName("tr");
var x=0;
for(x=0;x<3;x++){

tr[x].onmouseover=function(){tr[x] .style.backgroundColor='#11b006';
        };
tr[x].onmouseout=function(){tr[x] .style.backgroundColor='#f2f2f2';
        };    
      

}
}

      // 鼠标移动改变背景,可以通过给每行绑定鼠标移上事件和鼠标移除事件来改变所在行背景色。
     </script> 

</head>
<body>

<!--在删除按钮上添加点击事件 --> <!--在删除按钮上添加点击事件 -->
学号 姓名 操作
xh001 王小明 删除
xh002 刘小芳 删除
   <input type="button" value="添加一行"  onclick="add()"/>   <!--在添加按钮上添加点击事件  -->

</body>
</html>

ringa_lee
ringa_lee

ringa_lee

全部回覆(6)
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!