如何使用 jQuery 获取表格单元格值? [英] How to get a table cell value using jQuery?

查看:38
本文介绍了如何使用 jQuery 获取表格单元格值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I am trying to work out how to get the value of table cell for each row using jQuery.

My table looks like this:

<table id="mytable">
  <tr>
    <th>Customer Id</th>
    <th>Result</th>
  </tr>
  <tr>
    <td>123</td>
    <td></td>
  </tr>
  <tr>
    <td>456</td>
    <td></td>
  </tr>
  <tr>
    <td>789</td>
    <td></td>
  </tr>
</table>

I basically want to loop through the table, and get the value of the Customer Id column for each row.

In the code below I have worked out that I need to do this to get it looping through each row, but I'm not sure how to get the value of the first cell in the row.

$('#mytable tr').each(function() {
    var cutomerId = 
}

解决方案

If you can, it might be worth using a class attribute on the TD containing the customer ID so you can write:

$('#mytable tr').each(function() {
    var customerId = $(this).find(".customerIDCell").html();    
 });

Essentially this is the same as the other solutions (possibly because I copy-pasted), but has the advantage that you won't need to change the structure of your code if you move around the columns, or even put the customer ID into a <span>, provided you keep the class attribute with it.

By the way, I think you could do it in one selector:

$('#mytable .customerIDCell').each(function() {
  alert($(this).html());
});

If that makes things easier.

这篇关于如何使用 jQuery 获取表格单元格值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆