如何在JavaScript中遍历表行和单元格? [英] How do I iterate through table rows and cells in JavaScript?

查看:104
本文介绍了如何在JavaScript中遍历表行和单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个HTML表...说

If I have an HTML table...say

<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中检索每一行中每个单元格的值?

How would I iterate through all table rows (assuming the number of rows could change each time I check) and retrieve values from each cell in each row from within JavaScript?

推荐答案

如果你想要遍历每一行(< tr> ),知道/识别行(< tr> ),并遍历每一列(< td> )每行(< tr> ),然后就可以了。

If you want to go through each row(<tr>), knowing/identifying the row(<tr>), and iterate through each column(<td>) of each row(<tr>), then this is the way to go.

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> ),忽略你在哪一行,这就是你要走的路。

If you just want to go through the cells(<td>), ignoring which row you're on, then this is the way to go.

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
}

这篇关于如何在JavaScript中遍历表行和单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆