【发布时间】: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 计数器或者在你有
'<td>'+i+'</td>'的地方使用'<td>'+(index + 1)+'</td>'并摆脱那个奇怪的 for 循环 -
后者实际上解决了我的问题。非常感谢!
-
不客气 - 我已将其添加为答案
标签: javascript jquery loops for-loop html-table