JQuery, select first row of table

前端 未结 6 1008
清歌不尽
清歌不尽 2020-12-30 00:26

I\'ve used JQuery to add a \"image\" button to a few rows in a table. I used the following code:

$(\"#tblResults tr:nth-child(1) td.ResultsHeader span.gridRC         


        
相关标签:
6条回答
  • 2020-12-30 00:44

    jQuery is not necessary, you can use only javascript.

    <table id="table">
      <tr>...</tr>
      <tr>...</tr>
      <tr>...</tr>
       ......
      <tr>...</tr>
    </table>
    

    The table object has a collection of all rows.

    var myTable = document.getElementById('table');
    var rows =  myTable.rows;
    var firstRow = rows[0];
    
    0 讨论(0)
  • 2020-12-30 00:45

    Ok so if an image in a table is clicked you want the data of the first row of the table this image is in.

    //image click stuff here {
    $(this). // our image
    closest('table'). // Go upwards through our parents untill we hit the table
    children('tr:first'); // Select the first row we find
    
    var $row = $(this).closest('table').children('tr:first');
    

    parent() will only get the direct parent, closest should do what we want here. From jQuery docs: Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.

    0 讨论(0)
  • 2020-12-30 00:50

    This is a better solution, using:

    $("table tr:first-child").has('img')

    0 讨论(0)
  • 2020-12-30 00:56

    late in the game , but this worked for me:

    $("#container>table>tbody>tr:first").trigger('click');
    
    0 讨论(0)
  • 2020-12-30 00:56

    Can't you use the first selector ?

    something like: tr:first

    0 讨论(0)
  • 2020-12-30 00:58

    Actually, if you try to use function "children" it will not be succesfull because it's possible to the table has a first child like 'th'. So you have to use function 'find' instead.

    Wrong way:

    var $row = $(this).closest('table').children('tr:first');
    

    Correct way:

     var $row = $(this).closest('table').find('tr:first');
    
    0 讨论(0)
提交回复
热议问题