如何在JavaScript中遍历表行和单元格?

Gre*_*egH 174 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>
Run Code Online (Sandbox Code Playgroud)

我将如何遍历所有表行(假设每次检查时行数可能会更改)并从JavaScript中检索每行中每个单元格的值?

Joh*_*ock 275

如果你想要遍历每一行(<tr>),知道/识别row(<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
   }  
}
Run Code Online (Sandbox Code Playgroud)

如果你只是想通过细胞(<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
}
Run Code Online (Sandbox Code Playgroud)

  • @WilliamRemacle我差不多4年前发布了这个答案.当时IE 9甚至都没有想到! (5认同)
  • ex2,table.cells不兼容浏览器 (3认同)

dzi*_*ida 60

你可以考虑使用jQuery.使用jQuery,它非常简单,可能看起来像这样:

$('#mytab1 tr').each(function(){
    $(this).find('td').each(function(){
        //do your stuff, you can use $(this) to get current cell
    })
})
Run Code Online (Sandbox Code Playgroud)

  • 这是一个疯狂的政策.您可以随时将所需的相关功能从jQuery复制粘贴到您自己的应用程序代码中.除非有反对在线使用其他人的代码的政策,否则你不会在这里. (20认同)
  • @Judy:不同意"疯狂政策"......有很多理由不使用jQuery (13认同)
  • 不允许使用JQuery的另一个原因是嵌入式网站,例如我使用的是嵌入式WiFi芯片,整个网站只有250Kb.这是所有图像的挤压. (5认同)
  • 不能使用jquery ...公司不允许它.不要问为什么. (2认同)
  • jQuery 在你需要 2-3 个函数的地方毫无用处。使用 PHP 进行编码时速度缓慢且令人困惑。 (2认同)

sbr*_*bot 11

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
  }
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

在每次传递while循环时,r/c迭代器增加,并且集合中的新行/单元被分配给行/单元变量.当集合中不再有行/单元格时,false会被分配给行/单元格,而迭代则会循环停止(退出).


mwa*_*wag 7

更好的解决方案:使用 Javascript 的原生Array.from()并将 HTMLCollection 对象转换为数组,之后您可以使用标准数组函数。

var t = document.getElementById('mytab1');
if(t) {
    Array.from(t.rows).forEach((tr, row_ind) => {
        Array.from(tr.cells).forEach((cell, col_ind) => {
            console.log('Value at row/col [' + row_ind + ',' + col_ind + '] = ' + cell.textContent);
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

您也可以参考tr.rowIndexandcell.colIndex而不是使用row_indand col_ind

与前 2 个最高投票答案相比,我更喜欢这种方法,因为它不会使您的代码与全局变量ijrowcol混淆,因此它提供了干净、模块化的代码,不会产生任何副作用(或引发 lint / 编译器警告) ...没有其他库(例如jquery)。

如果您需要它在旧版本(ES2015 之前)的 Javascript 中运行,则Array.from可以使用 polyfill。


Kam*_*ski 6

尝试

for (let row of mytab1.rows) 
{
    for(let cell of row.cells) 
    {
       let val = cell.innerText; // your code below
    }
}
Run Code Online (Sandbox Code Playgroud)

for (let row of mytab1.rows) 
{
    for(let cell of row.cells) 
    {
       let val = cell.innerText; // your code below
    }
}
Run Code Online (Sandbox Code Playgroud)
for (let row of mytab1.rows) 
{
    for(let cell of row.cells) 
    {
       console.log(cell.innerText)
    }
}
Run Code Online (Sandbox Code Playgroud)

<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>
Run Code Online (Sandbox Code Playgroud)
for (let [i,row] of [...mytab1.rows].entries()) 
{
    for(let [j,cell] of [...row.cells].entries()) 
    {
       console.log(`[${i},${j}] = ${cell.innerText}`)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 干净我会说 (3认同)