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

这是一道慕课网上的练习题,在遍历数组设置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

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

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



原来的代码区




new document


学号 姓名 操作
xh001 王小明 删除
xh002 刘小芳 删除
 


ringa_lee
ringa_lee

ringa_lee

reply all (6)
阿神

不行的原因是因为,onmouseover出发时那个x得值是3,这又是一个闭包的问题。。。

    Peter_Zhu
           
      
    学号 姓名 操作
    xh001 王小明 删除
    xh002 刘小芳 删除

    建议使用jquery,方便,代码也简洁,少走弯路

      黄舟
      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'; }; }这个改成 for(let x=0;x<3;x++){ tr[x].onmouseover=function(){tr[x] .style.backgroundColor='#11b006'; }; tr[x].onmouseout=function(){tr[x] .style.backgroundColor='#f2f2f2'; }; }
        小葫芦
        /*var tr = document.getElementsByTagName("tr"); var x = 0; for (x = 0; x < 3; x++) { tr[x].onmouseover = function() { //console.log(x); //这是一个闭包问题。虽然tr确实绑定了函数,但是这个函数并没有保存每一次循环中的i的值,而在for循环之后i已经变为了3。这个函数找到的i就是3 //我们可以console一下,这里出现的是3,但是tr[3]这个元素存在吗?肯定不存在,所以不会有效果 tr[x].style.backgroundColor = '#11b006'; }; tr[x].onmouseout = function() { tr[x].style.backgroundColor = '#f2f2f2'; }; }*/ //改成 /*var tr = document.getElementsByTagName("tr"); var x = 0; for (x = 0; x < 3; x++) { //用闭包将每一次的i都传进去 tr[x].onmouseover = function(j) { return function() { tr[j].style.backgroundColor = '#11b006'; } }(x) tr[x].onmouseout = function(j) { return function() { tr[j].style.backgroundColor = '#f2f2f2'; } }(x) }*/ //还可以 var tr = document.getElementsByTagName("tr"); var x = 0; for (x = 0; x < 3; x++) { tr[x].onmouseover = function() { this.style.backgroundColor = '#11b006'; } tr[x].onmouseout = function(j) { this.style.backgroundColor = '#f2f2f2'; } }
          刘奇

          for循环里嵌套函数,会形成闭包问题,因为函数是不能自我执行的,所以按照解析顺序,for循环会循环结束,x的值最终为最后一个值,而当事件触发时,才会执行for循环里的函数,此时,函数获得的x值就是之前for循环循环完毕的最后一个值

            小葫芦
            for (x = 0; x < 3; x++) { tr[x].onmouseover = (function(x) { tr[x].style.backgroundColor = '#11b006'; })(x) }

            原来这里支持mk的写法啊~

              Latest Downloads
              More>
              Web Effects
              Website Source Code
              Website Materials
              Front End Template
              About us Disclaimer Sitemap
              php.cn:Public welfare online PHP training,Help PHP learners grow quickly!