如何获得第一个的id <tr>& lt; tbody>在HTML表格中使用jQuery

How to get the id of first <tr> of <tbody> in HTML table using jQuery?

本文关键字:表格 HTML jQuery tbody lt 第一个 id 何获得 tr      更新时间:2023-09-26

我有以下HTML表格:

<table id="blacklistgrid_1"  class="table table-bordered table-hover table-striped">
                      <thead>
                        <tr id="jumbo">
                          <th style="vertical-align:middle">Products</th>
                          <th style="vertical-align:middle">Pack Of</th>
                          <th style="vertical-align:middle">Quantity</th>
                          <th style="vertical-align:middle">Volume</th>
                          <th style="vertical-align:middle">Unit</th>
                          <th style="vertical-align:middle">Rebate Amount</th>
                        </tr>
                      </thead>
                      <tbody class="apnd-test">
                        <tr id="reb1_1">
<td><input type="text" name="pack[1]" id="pack_1" value="" class="form-control" size="8"/></td>
                          <td><input type="text" name="quantity[1]" id="quantity_1" value="" class="form-control" size="8"/></td>
                          <td><input type="text" name="volume[1]" id="volume_1" value="" class="form-control" size="8"/></td>
<td><input type="text" name="amount[1]" id="amount_1" value="" class="form-control" size="9"/></td>
</tr>
                      </tbody>
<tfoot>
                        <tr id="reb1_2">
                          <td><button style="float:right; margin-bottom: 20px" class="products" type="button" class="btn btn-default" onclick="">&nbsp;Add</button></td>
                          <td></td>
                          <td></td>
                          <td></td>
                          <td></td>
                          <td></td>
                        </tr>
                      </tfoot>                                           
                    </table>

现在我想获得第一行的id。本例中id为reb1_1。为了得到它,我尝试了下面的代码,但它没有工作。

$(document).ready(function() {
$('.products').click(function () {
var row = $(this).closest('table tbody:tr:first').attr('id');
    alert(row);
});
});

谢谢。

首先到table tbody,然后找到tr,然后像下面这样过滤第一行

var row = $(this).closest('table').find(' tbody tr:first').attr('id');

or can try

 var row = $(this).closest('table').find(' tbody tr:eq(0)').attr('id');
<<p>引用strong>:首先和: eq

按演示所示进行更改:-

http://jsfiddle.net/avmCX/38/

 $(document).ready(function() {
    $('.products').click(function () {
  var row = $(this).closest('table').find('tbody tr:first').attr('id');

        alert(row);
    });
    });

更多信息请看这里:-

http://api.jquery.com/first/

将函数改为:

$(document).ready(function() {
    $('.products').click(function () {
        var id =  $(this).closest("table").find("tbody>tr").first().attr("id");
        alert(id);
    });
});

将显示id。