перебрать HTML-таблицу и получить номер строки для каждой строки в JavaScript - PullRequest
0 голосов
/ 11 декабря 2018

Я хочу иметь возможность перебирать таблицу html, получать количество строк и выводить номер строки каждой строки в крайнем левом поле.Однако у меня есть 2 проблемы: не удается получить количество строк и не получить желаемый вывод.

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

      }
    }

Желаемый вывод:

Что я получил:

enter image description here

1 Ответ

0 голосов
/ 11 декабря 2018

Вы можете просто избавиться от цикла 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>';
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...