javascript - 将没有 id 的值写入 td?

标签 javascript jquery html

我需要编辑动态生成行/单元格的表中的值,因此它们没有 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/

相关文章:

javascript - Jquery 中的关联数组遍历每个元素

javascript - 使用jquery调用带变量的id文本区域

javascript - 下拉清除选项语义-ui

html - 可排序列表到复选框列表 JQuery,代码更改最少

javascript - 如何使用 jQuery 检测滚动条的移动?

javascript - 时间:2019-03-17 标签:c#xorcryptotojavascriptdecrypt

html - CSS:将 iFrame 定位到浏览器的右下角,可能吗?

html - 宽度不适用于 IE 9 中的类容器

javascript - 如何解决 Jest Test Code mockRestore 不起作用的问题

javascript - 如何动态地在 Owl Carousel 中创建新的幻灯片元素