2010-06-17 58 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

相关问题