jQuery如何获取td单元格值

jQuery How to get td cell value

本文关键字:td 单元格 获取 何获取 jQuery      更新时间:2023-09-26

当用户点击行的任何位置时,我正在尝试获取发票编号的值

下面是我的表

<div class="panel ui-widget-content" id="invoiceList">
<h2 class="ui-widget-header ui-corner-top" style="cursor: pointer; "><span>Invoices</span></h2>
    <table cellspacing='0' id='header' class="ui-widget">
        <tr>
            <th>Invoice Number</th>
             <th>Invoice Total</th>
        </tr>     
        <tr>
            <td><a href="#"  >INV-Error_Test1</a></td>
            <td>22.000000 USD</td>
        </tr>
        <tr>
            <td><a href="#"  >INV-Error_Test2</a></td>
           <td>22.000000 USD</td>
        </tr>
    </table> 
</div>

下面是我的jQuery,它只在点击Invoice Number字段时才提供发票编号

$("#invoiceList td").click(function (e) {
var result = $(this).text();
console.log('invoice --->'+result);
});

http://jsfiddle.net/5n62md3m/

当用户点击行上的任何位置时,有人能帮我获取发票号码吗。

检查一下,这可能是一个解决方案:

$('tbody tr').on('click', function(e){
   var value = $(this).find('td:first-child a').text();
  alert(value);
  e.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="panel ui-widget-content" id="invoiceList">
<h2 class="ui-widget-header ui-corner-top" style="cursor: pointer; "><span>Invoices</span></h2>
    <table cellspacing='0' id='header' class="ui-widget">
      <thead>
        <tr>
            <th>Invoice Number</th>
             <th>Invoice Total</th>
        </tr>
        </thead>
      <tbody>
        <tr>
            <td><a href="#"  >INV-Error_Test1</a></td>
            <td>22.000000 USD</td>
        </tr>
        <tr>
            <td><a href="#"  >INV-Error_Test2</a></td>
           <td>22.000000 USD</td>
        </tr>
        </tbody>
    </table> 
</div>

另一种替代解决方案可能是

$('#invoiceList tr:not(:first-child)').click(function(e){
   $tds = $(this).find("td");
   console.log( $tds.eq(0).text());
});
$("#invoiceList tr:not(:first-child)").click(function (e) {
    console.log('invoice ---> '+$(this).children('td:nth-child(1) a').text());
}

这里的一个小好处是,如果你想获得另一列,你只能更改nth-child中的数字(并可能删除后面的a)。