function tab(){
                var tabArr = $('tab').getElementsByTagName('a');
                var contArr = getElementsByClassName('hotestCont');
                
                for (var i = 0; i < tabArr.length; i++) {
                    (function(){
                        var j = i;
                        tabArr[i].onmouseover = function(){
                            this.className = 'here';
                            contArr[j].style.display = "block";
                        };
                        tabArr[i].onmouseout = function(){
                            this.className = '';
                            contArr[j].style.display = "none";
                        };
                        contArr[i].onmouseover = function(){
                            tabArr[j].className = 'here';
                            this.style.display = "block";
                        };
                        contArr[j].onmouseout = function(){
                            tabArr[j].className = '';
                            this.style.display = "none";
                        }
                    })();
                }
            }为什么for循环中(...)()这样写?
这样写有什么好处?
这种写法叫什么东东?

解决方案 »

  1.   

    可以正确的拿到i值.要不循环里的j就会得tabArr.length + 1
      

  2.   

    在定义 onmouseover处理函数 的时候,contArr[i]中i是个变量,只存在于for()循环中
    也就是 当onmouseover处理函数执行的时候i不存在了.
    通过(function(){})()的 方式,让匿名函数function(){}先执行一次,在这个过程中i还是有效的,
    可以借助参数或变量将i的值 保留在onmouseover处理函数定义中,
    这样onmouseover处理函数执行的时候 就相当于存在contArr[i]了.
      

  3.   

    这种写法叫做闭包
    <html><head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
    <title>test</title>
    <script>
    function tab(){
    var tabArr = document.getElementsByTagName('a');
    var arr = [1,2,3];
    for (var i = 0; i < tabArr.length; i++) {
    //(function(){
    var j = i;
    tabArr[i].onmouseover = function(){
    alert(arr[j]);
    };
    //})();
    }
    }
    </script>
    </head><body onload="tab()">
    去掉注释,加上注释,有什么不同?
    <a href="">a1</a>
    <a href="">a2</a>
    <a href="">a3</a>
    </body></html>