簡體   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