遍历html表并获取javascript中每一行的行号

时间:2018-12-11 15:34:26

标签: javascript jquery loops for-loop html-table

我希望能够遍历html表,获取行数,并在最左边的字段上输出每行的行号。但是,我有两个问题:无法获得行数和无法获得所需的输出。

$(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>';

      }
    }

所需的输出:

https://github.com/deeplearning4j/dl4j-examples/blob/master/rl4j-examples/

我得到了什么

1 个答案:

答案 0 :(得分:0)

您可以摆脱for循环,并使用每个循环的index加一个:

$.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>';
});