2010-06-17 57 views
127

如果我有一個HTML表...說如何迭代JavaScript中的表格行和單元格?

<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中?

回答

202

如果你想通過每一行(<tr>),明知/識別行(<tr>),並通過各行(<tr>)中的每一列(<td>)迭代,那麼這是要走的路。

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 
} 
+4

可能'row.cells [J]。 j ++)',對嗎? – maerics 2010-06-17 20:31:10

+2

謝謝你...複製粘貼錯誤。 – 2010-06-17 20:31:58

+3

ex2,table.cells isnt瀏覽器兼容 – EricG 2012-12-14 13:14:31

46

你可以考慮使用jQuery。與jQuery這是超級簡單,可能是這樣的:

$('#mytab1 tr').each(function(){ 
    $(this).find('td').each(function(){ 
     //do your stuff, you can use $(this) to get current cell 
    }) 
}) 
+1

無法使用jquery ...公司不允許它。不要問爲什麼。 – GregH 2010-06-17 20:46:57

+16

這是一個瘋狂的政策。您始終可以將您需要的相關函數從jQuery複製粘貼到您自己的應用程序代碼中。除非有政策禁止在線使用其他人的代碼,但是你不會在這裏。 – Judy 2011-04-01 00:39:51

+10

@Judy:對「瘋狂的政策」不同意......有很多不使用jQuery的原因 – Bigjim 2014-03-05 16:02:09

10

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>

在每次經過while循環R/C迭代增加和收集新的行/單元被分配到排/單元格變量。當集合中沒有更多行/單元格時,將false分配給行/單元格,並在while循環停止(退出)時進行迭代。

+0

上一篇: while(cell = row [r] .cells [C++] should be row.cells [C++],row is the current object,and a example for the sth code:mycoldata = cell.innerHTML – 2015-10-04 18:19:29

1

該解決方案完全爲我工作

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 = ""; 
    } 
} 
+0

那是甚至是JavaScript?因爲你的for循環看起來有點像PHP – Cubetastic 2017-09-28 13:30:14

+1

當你知道要尋找什麼時,很多語言都是非常相似的,PHP會在每個變量前面使用一個$,這不是。var也是一個關鍵字通過JavaScript,而不是PHP,但如果他們添加了它,我可能會錯過它 - 編輯 - gah沒有輸入換行...正如我所說:邏輯是普遍的知道如何將它轉錄成替代語言是一種非常有用的技能,它不是不容易學習 - 我們是具有優秀模式匹配能力的智力生物。識別每種語言之間的變化或者簡單地使用詞法分析器語言定義... – Acecool 2017-12-26 07:58:40

相關問題