如何在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中的每行单元格中检索值?
3 回答
慕无忌1623718
TA贡献1744条经验 获得超4个赞
<tr>
<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 } }
<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}
www说
TA贡献1775条经验 获得超8个赞
$('#mytab1 tr').each(function(){ $(this).find('td').each(function(){ //do your stuff, you can use $(this) to get current cell })})
慕婉清6462132
TA贡献1804条经验 获得超2个赞
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>
添加回答
举报
0/150
提交
取消