How to get a table cell value using jQuery?

后端 未结 9 1031
终归单人心
终归单人心 2020-11-22 14:41

I am trying to work out how to get the value of table cell for each row using jQuery.

My table looks like this:

相关标签:
9条回答
  • 2020-11-22 15:36
    $('#mytable tr').each(function() {
        var customerId = $(this).find("td:first").html();    
    });
    

    What you are doing is iterating through all the trs in the table, finding the first td in the current tr in the loop, and extracting its inner html.

    To select a particular cell, you can reference them with an index:

    $('#mytable tr').each(function() {
        var customerId = $(this).find("td").eq(2).html();    
    });
    

    In the above code, I will be retrieving the value of the third row (the index is zero-based, so the first cell index would be 0)


    Here's how you can do it without jQuery:

    var table = document.getElementById('mytable'), 
        rows = table.getElementsByTagName('tr'),
        i, j, cells, customerId;
    
    for (i = 0, j = rows.length; i < j; ++i) {
        cells = rows[i].getElementsByTagName('td');
        if (!cells.length) {
            continue;
        }
        customerId = cells[0].innerHTML;
    }
    

    0 讨论(0)
  • 2020-11-22 15:37
    $(document).ready(function() {
         var customerId
         $("#mytable td").click(function() {
         alert($(this).html());
         });
     });
    
    0 讨论(0)
  • 2020-11-22 15:41
    $('#mytable tr').each(function() {
      // need this to skip the first row
      if ($(this).find("td:first").length > 0) {
        var cutomerId = $(this).find("td:first").html();
      }
    });
    
    0 讨论(0)
提交回复
热议问题