表格的隔行变色

168 阅读1分钟

表格的隔行变色

1.获取所有的tr

 var trs = document.getElementsByTagName("tr");

2.隔行改变

forEach是数组的方法 然而 trs是一个伪数组。伪数组 :把其他所有长得像数组都被称为伪数组(类数组);

//1把伪数组转换成数组 :数组 =  Array.from("伪数组")
var arr =  Array.from( trs);//将伪数组转化成数组
//2通过forEach循环的 
arr.forEach(function(item,key){
            // console.log("forEach里的key值是:",key);
            // console.log("forEach里的item值是:",item);
            if(key%2==0){
                // console.log(item);
                // 改变所有索引是偶数的样式
                item.style.backgroundColor = "blue";
            }else{
                item.style.backgroundColor = "pink";
 })
//for循环和forEach的区别? forEach只能用于数组
   // trs.forEach(function(item){
        //     console.log(item);
        // })
        
  // for(var i=0;i<arr.length;i++){
       // 这个循环里的i值就等同于forEach循环的key值
       // for循环里的arr[i]等同于forEach里的 item
            console.log("for循环里的i值是:",i);
            console.log("for循环里arr[i]值是:",arr[i]);
// }