主页 M

javascript表格rows与cells运用,闭包的应用

2021-02-09 网页编程网 网页编程网

rows:表示表格所有行的集合;

cells:表示行内单元格的集合。

使用闭包来保存变量值:(只修改JS代码其它部分相同)

<script>
var tab=document.getElementById("tab");
for(var i=0,len=tab.rows.length;i<len;i++){
    for(var j=0,jlen=tab.rows[i].cells.length;j<jlen;j++){
        tab.rows[i].cells[j].innerHTML="("+i+","+j+")";
        //利用闭包产生作用域保存变量的值
        (function(row,col){
            tab.rows[row].cells[col].onmouseover=function(){
                if(row&&col){//row!=0,col!=0
                    tab.rows[0].cells[col].style.background="#f00";
                    tab.rows[row].cells[0].style.background="#f00";
                    this.style.background="#ff0";
                }
            }    
            tab.rows[row].cells[col].onmouseout=function(){
                if(row&&col){
                    tab.rows[0].cells[col].style.background="";
                    tab.rows[row].cells[0].style.background="";
                    this.style.background="";
                }
            }  
        })(i,j)
        
    }
}
</script>

阅读原文
阅读 2723
123 显示电脑版