请问如何在JavaScript中迭代表行和单元格?

如何在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中的每行单元格中检索值?



慕田峪9158850
浏览 294回答 3
3回答

慕无忌1623718

如果您想通过每一行(<tr>),知道/识别行(<tr>),并遍历每一列(<td>)每一行(<tr>),那么这就是该走的路了。var&nbsp;table&nbsp;=&nbsp;document.getElementById("mytab1");for&nbsp;(var&nbsp;i&nbsp;=&nbsp;0,&nbsp;row;&nbsp;row&nbsp;=&nbsp;table.rows[i];&nbsp;i++)&nbsp;{ &nbsp;&nbsp;&nbsp;//iterate&nbsp;through&nbsp;rows &nbsp;&nbsp;&nbsp;//rows&nbsp;would&nbsp;be&nbsp;accessed&nbsp;using&nbsp;the&nbsp;"row"&nbsp;variable&nbsp;assigned&nbsp;in&nbsp;the&nbsp;for&nbsp;loop &nbsp;&nbsp;&nbsp;for&nbsp;(var&nbsp;j&nbsp;=&nbsp;0,&nbsp;col;&nbsp;col&nbsp;=&nbsp;row.cells[j];&nbsp;j++)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//iterate&nbsp;through&nbsp;columns &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//columns&nbsp;would&nbsp;be&nbsp;accessed&nbsp;using&nbsp;the&nbsp;"col"&nbsp;variable&nbsp;assigned&nbsp;in&nbsp;the&nbsp;for&nbsp;loop &nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;}如果你只想穿过牢房<td>),忽略你在哪一行,那么这就是该走的路了。var&nbsp;table&nbsp;=&nbsp;document.getElementById("mytab1");for&nbsp;(var&nbsp;i&nbsp;=&nbsp;0,&nbsp;cell;&nbsp;cell&nbsp;=&nbsp;table.cells[i];&nbsp;i++)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//iterate&nbsp;through&nbsp;cells &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//cells&nbsp;would&nbsp;be&nbsp;accessed&nbsp;using&nbsp;the&nbsp;"cell"&nbsp;variable&nbsp;assigned&nbsp;in&nbsp;the&nbsp;for&nbsp;loop}

www说

您可以考虑使用jQuery。使用jQuery,它非常简单,看起来可能如下所示:$('#mytab1&nbsp;tr').each(function(){ &nbsp;&nbsp;&nbsp;&nbsp;$(this).find('td').each(function(){ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//do&nbsp;your&nbsp;stuff,&nbsp;you&nbsp;can&nbsp;use&nbsp;$(this)&nbsp;to&nbsp;get&nbsp;current&nbsp;cell &nbsp;&nbsp;&nbsp;&nbsp;})})

慕婉清6462132

var&nbsp;table=document.getElementById("mytab1");var&nbsp;r=0;while(row=table.rows[r++]){ &nbsp;&nbsp;var&nbsp;c=0; &nbsp;&nbsp;while(cell=row.cells[c++]) &nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;cell.innerHTML='[Row='+r+',Col='+c+']';&nbsp;//&nbsp;do&nbsp;sth&nbsp;with&nbsp;cell &nbsp;&nbsp;}}<table&nbsp;id="mytab1"> &nbsp;&nbsp;<tr> &nbsp;&nbsp;&nbsp;&nbsp;<td>A1</td><td>A2</td><td>A3</td> &nbsp;&nbsp;</tr> &nbsp;&nbsp;<tr> &nbsp;&nbsp;&nbsp;&nbsp;<td>B1</td><td>B2</td><td>B3</td> &nbsp;&nbsp;</tr> &nbsp;&nbsp;<tr> &nbsp;&nbsp;&nbsp;&nbsp;<td>C1</td><td>C2</td><td>C3</td> &nbsp;&nbsp;</tr></table>在每次遍历过程中,循环r/c迭代器增加,集合中的新行/单元格被分配给行/单元变量。当集合中没有更多的行/单元时,false被分配给行/单元格和迭代,然后循环停止(退出)。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript