使用jquery获取:
js代码:
$('#btntb').click(function(){
$('#tab tr').each(function(i){ // 遍历 tr
$(this).children('td').each(function(j){ // 遍历 tr 的各个 td
alert("第"+(i+1)+"行,第"+(j+1)+"个td的值:"+$(this).text()+"。");
});
});
});
使用js获取:
js代码:
var tb = document.getElementById('tab'); // table 的 id
var rows = tb.rows; // 获取表格所有行
for(var i = 0; i<rows.length; i++ ){
for(var j = 0; j<rows[i].cells.length; j++ ){ // 遍历该行的 td
alert("第"+(i+1)+"行,第"+(j+1)+"个td的值:"+rows[i].cells[j].innerHTML+"。"); // 输出每个td的内容
}
}
html代码:
<div align="center">
<table id="tab" border="1" align="center">
<tr>
<td>西瓜</td>
<td>橙</td>
</tr>
<tr>
<td>芒果</td>
<td>桔子</td>
</tr>
<tr>
<td>奇异果</td>
<td>葡萄</td>
<td>西柚</td>
</tr>
</table>
<br>
<button id="btntb">遍历table</button>
</div>