日期:2014-05-16  浏览次数:20332 次

帮忙解释下代码!
JScript code

<script type="text/javascript">
    var change=function(elem,att,val){
        elem.style[att]=val;
    }
    window.onload=function(){
        var buttons=document.getElementsByTagName("input");
                //这是几个按钮
        var box=document.getElementById("box");
        var att=["height","width","backgroundColor","display","display"];
        var val=["200px","200px","red","none","block"];
        for(var i=0;i<buttons.length;i++){
            buttons[i].index=i;
                        //给按钮分配index
            buttons[i].onclick=function(){
                change(box,att[this.index],val[this.index]);
                                //这里为什么用att[i],val[i]获取不到值呢,求解释
            }
        }
    }
</script>



为什么那行获取不到值呢,解释下原理吧,谢谢!

------解决方案--------------------
闭包问题,你若想直接使用i值

JScript code
        (function(i){
            buttons[i].onclick=function(){
                change(box,att[i],val[i]);
            }
        })(i)