1

我已经查看了有关如何遍历表的先前答案,但我无法让它工作。我一定是在做一些愚蠢的事情。这是一个例子:

我在 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

4 回答 4

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/

于 2013-10-09T10:17:52.837 回答
0

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

td {
    background-color:orange;
}

演示小提琴

于 2013-10-09T10:14:48.767 回答
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将遍历所有tds 和this函数内的关键字将引用当前循环td

于 2013-10-09T10:19:04.593 回答
0

为什么不用javascript创建表??? jsbin 演示

<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>
于 2013-10-09T10:53:12.667 回答