JavaScript遍歷table
1、說明
遍歷表格中的某行某列,並打印其值
2、實現源碼
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>JavaScript遍歷table</title> <style type="text/css"> tr td,tr th{ border:#CCC 1px solid; } </style> <script type="text/javascript"> /** * JavaScript遍歷table */ function eachTableRow() { //獲取table序號 var tab=document.getElementById("tab"); //獲取行數 var rows=tab.rows; //遍歷行 for(var i=1;i<rows.length;i++) { //遍歷表格列 for(var j=0;j<rows[i].cells.length;j++) { //打印某行某列的值 alert("第"+(i+1)+"行,第"+(j+1)+"列的值是:"+rows[i].cells[j].innerHTML); } } } </script> </head> <body> <table id="tab" cellpadding="0" cellspacing="0" style="width:50%; text-align:center; border:#CCC 1px solid;"> <tr style="border:#CCC 1px solid;"> <th>學號</th> <th>姓名</th> <th>年齡</th> <th>性別</th> </tr> <tr> <td>2014010101</td> <td>張思思</td> <td>20</td> <td>女</td> </tr> <tr> <td>2014010102</td> <td>立三</td> <td>21</td> <td>男</td> </tr> <tr> <td>2014010103</td> <td>王玉</td> <td>22</td> <td>女</td> </tr> <tr> <td>2014010104</td> <td>朱莉</td> <td>23</td> <td>男</td> </tr> </table> <input type="button" value="遍歷" onclick="eachTableRow()"/> </body> </html>
3、實現結果
(1)初始化時
(2)單擊“遍歷”
(3)再次單擊“遍歷”