繁体   English   中英

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

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

我希望能够遍历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>';

      }
    }

所需的输出:

我得到了:

在此处输入图片说明

您可以摆脱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>'; }); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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