如何遍历表的元素并更改JavaScript中每个元素的背景颜色?

时间:2013-10-09 10:07:48

标签: javascript css html-table

我已经看过以前的答案,如何遍历表格,我无法让它工作。我一定是在做一些愚蠢的事。这是一个例子:

我在CSS中有这个

td{width: 30px; height: 30px;
} 

<body onload = "setBackground();"> 

<table id = "table1"> 
    <tr id = "row1">
       <td>Stack</td>
       <td>Overflow</td>
       <td>Is my life saver</td>
    </tr>
</table> 

</body>

现在,在JS中我有这个

function setBackground() {

var table = document.getElementById("table1"); 

//i found this in a previous stack overflow answer and tried it

for (var i = 0, row; row = table.rows[i]; i++) { 

   for (var j = 0, col; col = row.cells[j]; j++) { 

  //this is for debugging purposes... I can't even get this to work
   alert(table.rows[i].cells[j]); 

   table.rows[i].cells[j].style.background = "orange"; //just an example

    }  
 }
}

请注意,我在我的body标签中调用该函数,但这不起作用。我一直试图解决这个问题,但我不能!另外,我不知道JQuery。如果有人可以帮助我,我会很感激。

4 个答案:

答案 0 :(得分:2)

不使用jquery:

(function() {
    function setBackground() {
        var table = document.getElementById("table1"); 

        //i found this in a previous stack overflow answer and tried it
        for (var i = 0, row; row = table.rows[i]; i++) { 
            for (var j = 0, col; col = row.cells[j]; j++) { 
                //this is for debugging purposes... I can't even get this to work
                alert(table.rows[i].cells[j]); 

                table.rows[i].cells[j].style.background = "orange"; //just an example
            }  
        }
    } 
    setBackground();
})();

您不需要body onload

在这里,您会找到:http://jsfiddle.net/h7ks4/

答案 1 :(得分:0)

为什么不像这样使用css为它着色

td {
    background-color:orange;
}

Demo Fiddle

答案 2 :(得分:0)

如果您愿意使用jQuery,可以试试这个:

$('#table1 td').css('background', 'orange');

但是如果你想执行一些更复杂的操作,请尝试.each函数

$('#table1 td').each(function(){
    $(this).css('background', 'orange');
    //or plain javascript if you prefer
    this.style.background = 'orange';
});

.each将遍历所有tdthis关键字,该函数将引用当前循环的td

答案 3 :(得分:0)

为什么不用javascript创建表? jsbin demo

<div id="tableContainer" >
    </div>



     <script>
      function setTable() {

var tableCntr= document.getElementById('tableContainer') ;
 var tblHTML = "<table>" ;

var colors = [['red','blue','green'],['orange', 'black', 'purple']]  ;

  for(var i=0;i<colors.length;i++) {
   tblHTML +="<tr>";

    for(var j=0;j<colors[0][0].length;j++) {
      tblHTML += "<td style='background:" + colors[i][j] + "'> </td>" ;
    }
       tblHTML += "</tr>" ;
 }
tblHTML +="</table>" ;
console.log(tblHTML);
tableCntr.innerHTML = tblHTML ;  
}


window.onload = setTable;
    </script>