jquery、js获取table,遍历输出tr中各个td的内容。


首先,依赖jquery..

1 $('#btntb').click(function(){
2    $('#tab tr').each(function(i){                   // 遍历 tr
3       $(this).children('td').each(function(j){  // 遍历 tr 的各个 td
4          alert("第"+(i+1)+"行,第"+(j+1)+"个td的值:"+$(this).text()+"。");
5       });
6    });
7 });

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>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM