javascript如何遍历表格数据
介绍如何使用js获取表格内某一单元格的内容,表格由table,tr,td等html标记组成。table表示表格,tr表示行,td表示行中列。
1、一般的表格结构如下
< table > < tr > < td >id</ td > < td >name</ td > </ tr > < tr > < td >1</ td > < td >fdipzone</ td > </ tr > < tr > < td >2</ td > < td >wing</ td > </ tr > </ table > |
2、遍历表格中所有内容方法
首先需要給table加上id,这样方便定位到哪一个表格,例如
<table id= "mytable" ></table> 获取表格行数 <script type= "text/javascript" > /** * 获取表格行数 * @param Int id 表格id * @return Int */ function getTableRowsLength(id){ var mytable = document.getElementById(id); return mytable.rows.length; } </script> |
获取表格某一行列数
<script type= "text/javascript" > /** * 获取表格某一行列数 * @param Int id 表格id * @param Int index 行数 * @return Int */ function getTableRowCellsLength(id, index){ var mytable = document.getElementById(id); if (index<mytable.rows.length){ return mytable.rows[index].cells.length; } else { return 0; } } </script> |
遍历表格内容保存到数组
<script type= "text/javascript" > /** * 遍历表格内容返回数组 * @param Int id 表格id * @return Array */ function getTableContent(id){ var mytable = document.getElementById(id); var data = []; for ( var i=0,rows=mytable.rows.length; i<rows; i++){ for ( var j=0,cells=mytable.rows[i].cells.length; j<cells; j++){ if (!data[i]){ data[i] = new Array(); } data[i][j] = mytable.rows[i].cells[j].innerHTML; } } return data; } </script> |
3、遍历表格内容完整例子
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> < html > < head > < meta http-equiv = "content-type" content = "text/html;charset=utf-8" > < title > 获取表格内容 </ title > < style type = "text/css" > table{width:300px; border:1px solid #000000; border-collapse:collapse;} td{border:1px solid #000000; border-collapse:collapse;} </ style > < script type = "text/javascript" > /** * 遍历表格内容返回数组 * @param Int id 表格id * @return Array */ function getTableContent(id){ var mytable = document.getElementById(id); var data = []; for(var i=0,rows=mytable.rows.length; i< rows ; i++){ for(var j = 0 , cells = mytable .rows[i].cells.length; j<cells; j++){ if(!data[i]){ data[i] = new Array(); } data[i][j] = mytable.rows[i].cells[j].innerHTML; } } return data; } /** * 显示表格内容 * @param Int id 表格id */ function showTableContent(id){ var data = getTableContent (id); var tmp = '' ; for( i = 0 , rows = data .length; i<rows; i++){ for( j = 0 , cells = data [i].length; j<cells; j++){ tmp += data[i][j] + ','; } tmp += '<br>'; } document.getElementById('result').innerHTML = tmp; } </ script > </ head > < body > < table id = "mytable" > < tr > < td >id</ td > < td >name</ td > </ tr > < tr > < td >1</ td > < td >fdipzone</ td > </ tr > < tr > < td >2</ td > < td >wing</ td > </ tr > </ table > < p >< input type = "button" name = "btn" value = "获取表格数据" onclick = "showTableContent('mytable')" ></ p > < p >< p id = "result" ></ p ></ p > </ body > </ html > |
以上就是javascript如何遍历表格数据的用法代码详解的详细内容,更多请关注php中文网其它相关文章!