我需要编辑动态生成行/单元格的表中的值,因此它们没有 html id。我目前通过转到 tr:nth-child 来执行此操作,但这仅在我为 rowID 设置的值对应于表中的该位置时才有效。例如:如果我从表中删除第三个项目,则 rowID=4 的项目现在是 tr 的第三个子项目,并且以下代码将编辑错误的单元格。
// I get the rowID like this:
rowID = $(this).data("row-id");
// This is what I'm doing now to edit the table:
$('#or-table tr:nth-child(' + rowID + ') td:nth-child(3)').html($('#aff-selector').val());
$('#or-table tr:nth-child(' + rowID + ') td:nth-child(4)').html($('#editor-code').val());
$('#or-table tr:nth-child(' + rowID + ') td:nth-child(5)').html($('#editor-lat').val());
$('#or-table tr:nth-child(' + rowID + ') td:nth-child(6)').html($('#editor-long').val());
<!-- This is the table: -->
<table id="or-table" class="table table-condensed table-hover table-striped bootgrid-table">
<thead>
<tr>
<th data-column-id="id" data-identifier="true" data-type="numeric">ID</th>
<th data-column-id="aff" align="center">Affiliation</th>
<th data-column-id="code">Symbol Code</th>
<th data-column-id="lat">Latitude</th>
<th data-column-id="long">Longitude</th>
<th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th>
</tr>
</thead>
<tbody></tbody>
</table>
最佳答案
您可以使用 for 循环动态分配行 ID,然后在每次删除行时重做该计算。
function foo () {
var rowCount = $('#or-table tbody tr').length;
for (i=1;i <= rowCount; i++) {
$('#or-table tbody tr:nth-child("'+i+'")').data('row', i);
}
}
您可以在 $(document).ready 上运行此函数,并在删除任何行后再次运行此函数。
关于javascript - 将没有 id 的值写入 td?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38905841/