Jquery- Get the value of first td in table

后端 未结 6 2345
旧巷少年郎
旧巷少年郎 2020-12-03 02:51

I am trying to get the value of first td in each tr when a users clicks \"click\".

The result below will output aa ,ee or ii. I was thinking about using closest(\'t

相关标签:
6条回答
  • 2020-12-03 03:07

    This should work:

    $(".hit").click(function(){    
       var value=$(this).closest('tr').children('td:first').text();
       alert(value);    
    });
    

    Explanation:

    • .closest('tr') gets the nearest ancestor that is a <tr> element (so in this case the row where the <a> element is in).
    • .children('td:first') gets all the children of this element, but with the :first selector we reduce it to the first <td> element.
    • .text() gets the text inside the element

    As you can see from the other answers, there is more than only one way to do this.

    0 讨论(0)
  • 2020-12-03 03:07

    In the specific case above, you could do parent/child juggling.

    $(this).parents("tr").children("td:first").text()
    
    0 讨论(0)
  • 2020-12-03 03:11
    $(this).parent().siblings(":first").text()
    

    parent gives you the <td> around the link,

    siblings gives all the <td> tags in that <tr>,

    :first gives the first matched element in the set.

    text() gives the contents of the tag.

    0 讨论(0)
  • 2020-12-03 03:20
    $(".hit").click(function(){
       var values = [];
       var table = $(this).closest("table");
       table.find("tr").each(function() {
          values.push($(this).find("td:first").html());
       });
    
       alert(values);    
    });
    

    You should avoid $(".hit") it's really inefficient. Try using event delegation instead.

    0 讨论(0)
  • 2020-12-03 03:20

    Install firebug and use console.log instead of alert. Then you will see the exact element your accessing.

    0 讨论(0)
  • 2020-12-03 03:27

    If you need to get all td's inside tr without defining id for them, you can use the code below :

    var items = new Array();
    
    $('#TABLE_ID td:nth-child(1)').each(function () {
          items.push($(this).html());
    });
    

    The code above will add all first cells inside the Table into an Array variable.

    you can change nth-child(1) which means the first cell to any cell number you need.

    hope this code helps you.

    0 讨论(0)
提交回复
热议问题