慕田峪9158850
2019-08-02 07:02:57
如何在JavaScript中迭代表行和單元格?如果我有一個(gè)HTML表.比如說(shuō)<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>我將如何迭代所有表行(假設(shè)每次檢查時(shí)行數(shù)都會(huì)改變),并從JavaScript中的每行單元格中檢索值?
3 回答

慕無(wú)忌1623718
TA貢獻(xiàn)1744條經(jīng)驗(yàn) 獲得超4個(gè)贊
<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說(shuō)
TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超8個(gè)贊
$('#mytab1 tr').each(function(){ $(this).find('td').each(function(){ //do your stuff, you can use $(this) to get current cell })})

慕婉清6462132
TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超2個(gè)贊
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>
添加回答
舉報(bào)
0/150
提交
取消