如何迭代JavaScript中的表格行和单元格?
如果我有一个HTML表…说
<div id="myTabDiv"> <table name="mytab" id="mytab1"> <tr> <td>col1 Val1</td> <td>col2 Val2</td> </tr> <tr> <td>col1 Val3</td> <td>col2 Val4</td> </tr> </table> </div>
我将如何遍历所有的表行(假设每次我检查行的数量可以改变),并从JavaScript中的每一行中的每个单元格检索值?
如果你想遍历每行( <tr>
),知道/识别行( <tr>
),并遍历每行( <tr>
)的每一列( <td>
<tr>
),那么这是走。
var table = document.getElementById("mytab1"); for (var i = 0, row; row = table.rows[i]; i++) { //iterate through rows //rows would be accessed using the "row" variable assigned in the for loop for (var j = 0, col; col = row.cells[j]; j++) { //iterate through columns //columns would be accessed using the "col" variable assigned in the for loop } }
如果你只想通过单元格( <td>
),忽略你所在的行,那么这就是要走的路。
var table = document.getElementById("mytab1"); for (var i = 0, cell; cell = table.cells[i]; i++) { //iterate through cells //cells would be accessed using the "cell" variable assigned in the for loop }
你可以考虑使用jQuery。 使用jQuery这非常简单,可能看起来像这样:
$('#mytab1 tr').each(function(){ $(this).find('td').each(function(){ //do your stuff, you can use $(this) to get current cell }) })
var table=document.getElementById("mytab1"); var r=0; while(row=table.rows[r++]) { var c=0; while(cell=row.cells[c++]) { cell.innerHTML='[Row='+r+',Col='+c+']'; // do sth with cell } }
<table id="mytab1"> <tr> <td>A1</td><td>A2</td><td>A3</td> </tr> <tr> <td>B1</td><td>B2</td><td>B3</td> </tr> <tr> <td>C1</td><td>C2</td><td>C3</td> </tr> </table>
这个解决scheme对我来说非常合适
var table = document.getElementById("myTable").rows; var y; for(i = 0; i < # of rows; i++) { for(j = 0; j < # of columns; j++) { y = table[i].cells; //do something with cells in a row y[j].innerHTML = ""; } }