簡體   English   中英

如何獲得第一個id <tr> 的 <tbody> 在HTML表格中使用jQuery?

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

我跟着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);
});

});

謝謝。

首先去表tbody然后找到tr然后過濾第一行,如下所示

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

或者可以試試

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

參考:第一和: 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);
    });
});

這將顯示你的身份。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM