Getting the id of the first row in tbody with jquery

时间:2017-06-20 12:36:33

标签: jquery html

I have some HTML like this:

 <tbody id="box_id">
        @foreach($documents as $document)
        <tr id="row_{{$document->id}}">
         ...
       </tr>
      @endforeach
  </tbody>

And some Jquery like this:

$(document).keydown(function(e) {
    switch(e.which) {

    case 38: // up

            var row = $('#box_id').find('tbody tr:first').attr('id');
            alert(row);



        break;
           ...

I want to get the id of the first row in the tbody when I press up. It keeps alerting undefined. Any suggestions?

3 个答案:

答案 0 :(得分:3)

Use it as $('#box_id').find('tr:first').attr('id') as box_id is the id of tbody itself.

答案 1 :(得分:1)

As per your code you are finding tbody tr inside tbody.. Just update your code with following..

$(document).keydown(function(e) {
    switch(e.which) {
    case 38: // up
        var row = $('#box_id').find('tr:first').attr('id');
        alert(row);
    break;

答案 2 :(得分:1)

你已经在tbody,所以你不会找到其他人。请尝试以下代码:

$('#box_id').find('tr:first').attr('id');

......甚至更好:

$('#box_id > tr:first').attr('id');