javascript - 按 ID 查找表格行并编辑其单元格?

标签 javascript jquery html

我需要编辑表中的值,其中行/单元格是由 Bootgrid 动态生成的,因此它们没有 html id。我目前通过转到 tr:nth-child 来执行此操作,但这仅在我为 rowID 设置的值对应于表中的该位置时才有效。

例如:如果我从表中删除第三个项目,则 rowID=4 的项目现在是 tr 的第三个子项目,并且以下代码将编辑错误的单元格。

我需要能够找到正确的行以按 ID 进行编辑,而不是按网格中的位置进行编辑。我昨天发布了类似的问题,但我对此进行了改进,以更好地阐明我想要做什么。

// I get the rowID by clicking an Edit button on the table row, 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>
      <!-- These tr/td generated by Bootgrid: -->
      <tr data-row-id="1">
        <td class="select-cell" style="{{ctx.style}}">
        <td class="text-left" style="">1</td>
        <td class="text-left" style="">H</td>
        <td class="text-left" style="">SHG-EVAI-------</td>
        <td class="text-left" style="">35.39135902572556</td>
        <td class="text-left" style="">-116.52048110961914</td>
        <td class="text-left" style="">
      </tr>
      <tr data-row-id="2">
        <td class="select-cell" style="{{ctx.style}}">
        <td class="text-left" style="">2</td>
        <td class="text-left" style="">H</td>
        <td class="text-left" style="">SHG-EVAT-------</td>
        <td class="text-left" style="">35.40241360341436</td>
        <td class="text-left" style="">-116.52648925781249</td>
        <td class="text-left" style="">
      </tr>      
    </tbody>
</table>

最佳答案

您可以使用以下选择器

$("#or-table tr[data-row-id='2']")

选择相关的tr元素。

显然,您应该根据您想要实现的目标更改 2 值:)

关于javascript - 按 ID 查找表格行并编辑其单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38919536/

相关文章:

javascript - 在调用 ngOnInit() 之前,Angular 构造函数不会设置局部变量

javascript - 单击 anchor 链接返回 NULL 作为偏移量

javascript - 在 PHP 中发布选项文本而不是值

javascript - 我应该先学习 jQuery 或 Javascript,还是同时学习?

javascript - 使用键对对象数组进行排序

javascript - AngularJS 表单验证 - TypeError : Cannot set property 'integer' of undefined

javascript - 为每个领域使用react OnChange - 有没有更好的方法

python - 如何使用 Pandas 从文件中提取 html 表格?

jquery - 如何只显示最后一次出现的元素?

javascript - 即使从未提交表单,也使用 html5 验证?