简体   繁体   中英

iterate through a html table and get row number for each row in javascript

I want to be able to iterate though a html table, get the number of rows, and output the row number of each row on the leftmost field. However, I have 2 problems: not being able to get the number of rows and not getting the desired output.

$(document).ready(function($) {
      function create_html_table(tbl_data) {

        var tbl = '';
        tbl += '<table id ="datarepo">';
        tbl += '<thead>';
        //Some headers          
        tbl += '</thead>';
        tbl += '<tbody>';

        $.each(tbl_data, function(index, val) {

          /* This is what I want to use to get the number of rows in the table. 
           However, uncommenting the following line will cause the whole table to disappear altogether.*/
          // var numberrows = document.getElementById("datarepo").rows.length;

          // Using static value here instead of numberrows because it is not working. 
          for (i = 1; i <= 2; i++) {
            tbl += '<tr>';
            tbl += '<td >' + i + '</td>';
            tbl += '<td ><div col_name="filename">' + val['filename'] + '</div></td>';

            tbl += '</tr>';
          }
        });

        tbl += '</tbody>';
        tbl += '</table>';

      }
    }

Desired output:

What I got:

在此处输入图片说明

You can just get rid of your for loop and use the index of the each loop plus one:

 $.each(tbl_data, function(index, val) { tbl += '<tr>'; tbl += '<td >' + (index + 1) + '</td>'; tbl += '<td ><div col_name="filename">' + val['filename'] + '</div></td>'; tbl += '</tr>'; }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM