【问题标题】:iterate through a html table and get row number for each row in javascript遍历 html 表并获取 javascript 中每一行的行号
【发布时间】:2019-05-12 15:20:18
【问题描述】:

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

      }
    }

期望的输出:

我得到了什么:

【问题讨论】:

  • 为什么不直接使用 css 计数器或者在你有 '&lt;td&gt;'+i+'&lt;/td&gt;' 的地方使用 '&lt;td&gt;'+(index + 1)+'&lt;/td&gt;' 并摆脱那个奇怪的 for 循环
  • 后者实际上解决了我的问题。非常感谢!
  • 不客气 - 我已将其添加为答案

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    相关资源
    最近更新 更多